问题描述
总结我的问题,
我想要一个数组返回两个数组指针。这些指针数组之一必须为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;
}