我正在尝试学习调用函数,但遇到了一个问题,我被告知我需要声明 a
, b
, c
和 d
,但程序的重点是提示用户输入这些数字,然后将它们相加。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int f(int a, int b, int c, int d);
int g(int b, int c, int d);
int h(int c, int d);
int i(int d);
int
main(int argc,char **argv)
{
int result;
result = f(a,b,c,d);
printf("Value of a?");
scanf("%d",a);
printf("Value of b?");
scanf("%d",b);
printf("Value of c?");
scanf("%d",c);
printf("Value of d?");
scanf("%d",d);
printf("Your result is %d",result);
return 0;
}
int
f(int a, int b, int c, int d)
{
return a + g(b,c,d);
}
int
g(int b, int c, int d)
{
return b + h(c,d);
}
int
h(int c, int d)
{
return c + i(d);
}
int
i(int d)
{
return d + d;
}
具体警告是
call.c:16:13: error: ‘a’ undeclared (first use in this function)
result = f(a,b,c,d);
并且对 b、c 和 d 重复。
谁能告诉我我做错了什么?我将函数签名放在 int a
、int b
、int c
和 int d
所在的顶部已经定义了,所以我对我做错了什么感到困惑。
编辑:问题已解决!代码应该类似于
int result;
int a;
int b;
int c;
int d;
printf("Value of a?");
scanf("%d",&a);
printf("Value of b?");
scanf("%d",&b);
printf("Value of c?");
scanf("%d",&c);
printf("Value of d?");
scanf("%d",&d);
result = f(a,b,c,d);
printf("Your result is %d",result);
return 0;
最佳答案
您需要在 main 中声明这些变量,尝试将代码更改为
int 结果,a、b、c、d;
此外,scanf
还需要参数的可变参数部分中的指针,
因此您需要使用 &
引用运算符来获取 a
示例:scanf("%d", &a);
对所有 scanf
调用执行此操作。
关于c - 当我提示用户输入变量时,如何声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25881348/