繁体   English   中英

简单 C 程序的不可预测的输出

[英]Unpredictable output of simple C Program

我从一开始就在练习c编程,但是当我执行简单的C程序将两个数字相加时,我得到了意想不到的输出,我无法弄清楚,谁能提供编译器在幕后如何工作的详细说明对于这个输出。

这是提到的代码。 我正在使用基本的 Turbo IDE

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c=0;
clrscr();
printf("Enter two numbers:");
scanf("%d%d", &a,&b);
c=a+b;
printf("sum of two numbers are %d", &c);
getch();
}


Output:

Enter two numbers:1
2
sum of two numbers are -16

你有错误:-

printf("sum of two numbers are %d", &c);`

将其更改为:-

printf("sum of two numbers are %d", c);

&c用于打印地址。

修改后的代码:-

#include <stdio.h>
#include <conio.h>
void main()
{
    int a, b, c = 0;
    clrscr();
    printf("Enter two numbers:");
    scanf("%d%d", &a, &b);
    c = a + b;
    printf("sum of two numbers are %d", c); // not &c
    getch();
}

输出 :-

Enter two numbers:3                                                                                                                                                                    
5                                                                                                                                                                                      
sum of two numbers are 8  

Turbo c 已经过时了。试试gcc (像 CodeBlocks 这样的 IDE) 另外,还要确保你的代码是否正确预期

问题似乎是您在不需要的变量c上使用了地址运算符。 &c是一个指向c ,所以当你打印出来,你实际上是试图打印的内存地址c ,而不是存储在那里的整数值,从而导致意外的输出。 所以

printf("sum of two numbers are %d", &c);

应该成为

printf("sum of two numbers are %d", c);

您输入的printf语法错误,请使用以下命令: printf("sum of two numbers are %d",c);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM