代码可以很好地运行DevC++,但不能运行Visual Studio代码
正在做一个家庭作业题。简单的代码将两个整数相加。代码看起来很好,但是运行它总是给我错误的结果。在我失去理智后,我尝试在DevC++中运行它,它给了我我所期望的结果。
我对编码是非常非常陌生的。Visual Studio代码试图在输出窗口中告诉我一些东西,但我不知道它试图告诉我的是什么。
#include <stdio.h>
int main()
{
double x,y,z;
printf("Enter first number:" );
scanf("%i", &x);
printf("Enter second number:" );
scanf("%i", &y);
printf("the first number is: %d \n",x);
printf("the second number is: %d \n ",y);
z= x+y;
printf("Output 1: The result is %d . \n",z);
printf("Output 2: The sum of %d and %d is %d . ",x,y,z);
return 0;
}
hwidk.cpp:19:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
printf("Output 1: The result is %d . \n",z);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~
[hwidk.cpp 2019-05-27 21:35:01.608]
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
printf("Output 2: The sum of %d and %d is %d . ",x,y,z);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 3 has type 'double' [-Wformat=]
[hwidk.cpp 2019-05-27 21:35:01.608]
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 4 has type 'double' [-Wformat=]
-Visual Studio运行代码为
Enter first number:5
Enter second number:6
the first number is: 5
the second number is: 6
Output 1: The result is 7 .
Output 2: The sum of 5 and 0 is 6
发布于 2019-05-28 06:16:06
用于scanf
和printf
调用的格式字符串是错误的。因为你的变量是双精度的,所以你应该使用%f
。%d
用于整数。
Visual Studio会在可能的情况下对printf
参数进行一些分析,并警告您该问题。DevC++显然不会这样做,所以它不会生成警告。
这种行为在这两种编译器中都是未定义的,而且您很不幸,似乎可以使用DevC++。
发布于 2019-05-28 06:10:17
我认为DevC++使用的编译器与VS代码使用的编译器不同,主要问题出在printf
中。您正在使用%d
,这意味着一个integer
参数,但是您正在向它传递一个double
。DevC++编译器可能会自动将双精度值截断为整数值。将它切换到%f应该可以解决问题
https://stackoverflow.com/questions/56332907
复制相似问题