c - 由于 %,printf 中的 c 程序出错
问题描述
我正在 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;
}
error: Enter the value of x
2 Enter the value of y
1 矩形的面积是-293795784 // 这是错误。我期待输出 2,即 x 和 y 的乘积不知道为什么它采用值的地址而不是值。
解决方案
在 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;
}
您还需要检查来自的返回值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;
}
推荐阅读
- django - 从 ember 发送 POST 请求到指定的 URL
- qt - QObjectPicker 不适用于自定义几何网格和渲染器
- c - 汇编代码如何确定变量在堆栈中的位置?
- c# - c# .Net Core DI:从 ServiceProvider 请求一个泛型接口的实现,其中泛型属性仅在运行时才知道
- sql - 使用 sql 代码/函数将 Salesforce ID 从 15 位转换为 18 位
- android - 如何从 TextureView 中的相机预览中获取条形码行值?
- android-studio - Backspace button removing only one previous character in Android Studio
- python - 沿numpy数组的任意轴迭代连续的一维切片
- javascript - 使用 HTML 拖放 API 中使用的光标值
- javascript - 无法使用 select2 读取 null 的属性“查询”