首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SImple代码可以在DevC++中正常运行,但Visual Studio代码无法正常运行

SImple代码可以在DevC++中正常运行,但Visual Studio代码无法正常运行
EN

Stack Overflow用户
提问于 2019-05-28 06:05:33
回答 2查看 140关注 0票数 -2

代码可以很好地运行DevC++,但不能运行Visual Studio代码

正在做一个家庭作业题。简单的代码将两个整数相加。代码看起来很好,但是运行它总是给我错误的结果。在我失去理智后,我尝试在DevC++中运行它,它给了我我所期望的结果。

我对编码是非常非常陌生的。Visual Studio代码试图在输出窗口中告诉我一些东西,但我不知道它试图告诉我的是什么。

代码语言:javascript
运行
复制
#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;
}

代码语言:javascript
运行
复制
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运行代码为

代码语言:javascript
运行
复制
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
EN

回答 2

Stack Overflow用户

发布于 2019-05-28 06:16:06

用于scanfprintf调用的格式字符串是错误的。因为你的变量是双精度的,所以你应该使用%f%d用于整数。

Visual Studio会在可能的情况下对printf参数进行一些分析,并警告您该问题。DevC++显然不会这样做,所以它不会生成警告。

这种行为在这两种编译器中都是未定义的,而且您很不幸,似乎可以使用DevC++。

票数 2
EN

Stack Overflow用户

发布于 2019-05-28 06:10:17

我认为DevC++使用的编译器与VS代码使用的编译器不同,主要问题出在printf中。您正在使用%d,这意味着一个integer参数,但是您正在向它传递一个double。DevC++编译器可能会自动将双精度值截断为整数值。将它切换到%f应该可以解决问题

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56332907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档