【发布时间】:2021-11-14 11:54:46
【问题描述】:
仅限 C 语言。
当我运行此代码时,我在第 7 行收到错误消息:
warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int **’ [-Wformat=]
另外,我在第 8 行收到错误消息:
warining: function returns address of local variable [-Wreturn-local-addr]
我附上了一张我想要输出的图片。有人可以显示更正的代码吗,不胜感激,谢谢!
#include <stdio.h>
// Method getFraction() asks for numerator and denominator
int *getFraction() {
int *n[2]; // declare array of pointers to return the numerator and
// denominator
printf("\n Enter the numerator and the denominator -- ");
scanf("%d%d", (n + 0), (n + 1)); // read numerator and denominator
return n; // return n
}
// method smallest() takes twointegers as its parameter and return the smallest
int smallest(int a, int b) {
if (a < b) // condition for a is smallest
return a; // return a
else
return b; // return b
}
// recursive method to return the GCD() of two numbers
int gcd(int a, int b) {
if (b == 0) // if denominator is 0 then return a
return a;
// recursively call to gcd()
return gcd(b, a % b);
}
// method reduce() takes two parameters as call by reference and
// reduce the fraction
void reduce(int *a, int *b) {
int g;
// call to gcd()
g = gcd(*a, *b);
// reduce numerator
*a = *a / g;
// reduce denominator
*b = *b / g;
}
// driver code
int main() {
int *num, a, b, small, g;
char ch;
// loop to repeat the process till user wants
do {
num = getFraction(); // call to getFraction();
a = *(num + 0); // assign numerator to a
b = *(num + 1); // assign denominator to b
// condition for denominator not zero
if (b != 0) {
reduce(&a, &b); // call to reduce() as call by reference
// print the reduced fraction
printf("\n The reduced fraction is -- %d / %d", a, b);
}
else printf("\n Denominator should not be zero.");
// ask user to repeat more
printf("\n Try again (Y/N) -- ");
fflush(stdin);
scanf("%c", &ch); // read users choice
} while (ch == 'y' || ch == 'Y');
return 0;
}
【问题讨论】:
-
为什么是
int *n[2];而不是int n[2];?你永远不会分配内存,所以读入n[0]和n[1]会使程序有未定义的行为 -
请正确格式化您的代码,以便可以按原样复制并成功编译。目前,它的格式很差。
-
你传递
n这是数组本身的地址(不是它未初始化的指针内容)。建议你重构一下函数,比如void getFraction(int n[2])