微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

返回数组的两个指针

如何解决返回数组的两个指针

总结我的问题, 我想要一个数组返回两个数组指针。这些指针数组之一必须为float或double,这将为我提供商操作。另一个应该是int,并且应该给出除法的其余部分。
例如,如果我有两个数组,例如:int a[] = {3,6,9,12,16,18},b[] = {2,3,4,4};,当我想到达指针时,结果应类似于:Quotient is: {1.5,2,4.5} Remainder is: {1,2}
这是我的代码

#include<stdio.h>

void div(int a[],int b[],float *quotient,int *remainder) {
    float quo[6];
    int remain[6];

    for(int i = 0; i< 6 ; i++)
    {
        quo[i] = a[i] / (double)b[i];
        remain[i] = a[i] % b[i];
        *remainder = remain[i];
        *quotient = quo[i];
        *remainder++;
        *quotient++;
    }

   // quotient = quo;
   // remainder = remain;
 
}

int main() {

    int a[] = {3,4};
    float q;
    int r;
  
    div(a,b,&q,&r);

    for(int i = 0; i< 6 ; i++)
    {

        printf("Quotient is: %.1f\nRemainder is: %d\n",q,r);
    } 


 //  printf("Quotient is: %.1f\nRemainder is: %d\n",*q,*r);
   return 0;
}

解决方法

您需要将商和余数的数组传递到除法函数中。 函数返回后,您将无法读取这些值。

#include<stdio.h>

void div(int* a,int* b,float* quotient,int* remainder,int count) {

    for (int i = 0; i < count; i++)
    {
        quotient[i] = a[i] / (double)b[i];
        remainder[i] = a[i] % b[i];
    }
}


int main() {

    int a[] = { 3,6,9,12,16,18 },b[] = { 2,3,4,4 };

#define LENGTH  (sizeof(a) / sizeof(int))
    
    float quotient[LENGTH];
    int remainder[LENGTH];


    div(a,b,quotient,remainder,LENGTH);

    for (int i = 0; i < LENGTH; i++)
    {

        printf("Quotient is: %.1f\nRemainder is: %d\n",quotient[i],remainder[i]);
    }
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。