首页 > 解决方案 > 由于 %,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 的乘积不知道为什么它采用值的地址而不是值。

标签: cvisual-studio-2010

解决方案


在 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;

}

推荐阅读