我正在 Visual Studio 中编写我的第一个 c 程序,并且由于格式说明符而出现非常基本的错误。
#include <stdio.h>
int main()
{
int x,y;
int area = x*y;
printf("Enter the value of x \n");
scanf("%d", &x);
printf("Enter the value of y \n");
scanf("%d", &y);
printf("Area of the rectangle is %d\n", area);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
error: Enter the value of x
2 Enter the value of y
1 矩形的面积是-293795784 // 这是错误。我期待输出 2,即 x 和 y 的乘积 不确定为什么它采用值的地址而不是值。
小智 5
我们无法找到 x 和 y 初始化之前的区域!
#include <stdio.h>
int main()
{
int x,y;
printf("Enter the value of x \n");
scanf("%d", &x);
printf("Enter the value of y \n");
scanf("%d", &y);
//Put this area formula here
int area = x*y;
printf("Area of the rectangle is %d\n", area);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您还需要检查来自scanf. 那就是 - 检查是否scanf实际扫描了一个整数。换句话说:当你想读取 1 个整数时,检查scanf返回 1。如果不是,则有错误。
这就像:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,y;
printf("Enter the value of x \n");
if (scanf("%d", &x) != 1) // Notice this line
{
// Wrong input - stop program
fprintf(stderr,"Input error - input must be a number\n");
exit(1);
};
printf("Enter the value of y \n");
if (scanf("%d", &y) != 1) // Notice this line
{
// Wrong input - stop program
fprintf(stderr,"Input error - input must be a number\n");
exit(1);
};
//Put this area formula here
int area = x*y;
printf("Area of the rectangle is %d\n", area);
return 0;
}
Run Code Online (Sandbox Code Playgroud)