[英]Unpredictable output of simple C Program
I am practicing c programming from the very beginning, but when I execute simple C program to add two numbers, I got unexpected output, I am not able to figure it out, can anyone provide the detailed explanation of how the compiler works behind the scene for this output.我从一开始就在练习c编程,但是当我执行简单的C程序将两个数字相加时,我得到了意想不到的输出,我无法弄清楚,谁能提供编译器在幕后如何工作的详细说明对于这个输出。
Here is the mentioned code.这是提到的代码。 I am using basic turbo IDE
我正在使用基本的 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
You have mistake in line :-你有错误:-
printf("sum of two numbers are %d", &c);`
Change it to :-将其更改为:-
printf("sum of two numbers are %d", c);
&c
is used when you want to print address. &c
用于打印地址。
Modified code :-修改后的代码:-
#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();
}
Output :-输出 :-
Enter two numbers:3
5
sum of two numbers are 8
Turbo c is very outdated.Try gcc
(IDEs like CodeBlocks) . Turbo c 已经过时了。试试
gcc
(像 CodeBlocks 这样的 IDE) 。 Also make sure that your code is intended properly.另外,还要确保你的代码是否正确预期。
The problem seems to be that you used the address-of operator on the variable c
where you did not need to.问题似乎是您在不需要的变量
c
上使用了地址运算符。 &c
is a pointer to c
, so when you print it out you are actually trying to print the memory address of c
rather than the integer value stored there, leading to unexpected output. &c
是一个指向c
,所以当你打印出来,你实际上是试图打印的内存地址c
,而不是存储在那里的整数值,从而导致意外的输出。 So所以
printf("sum of two numbers are %d", &c);
should become应该成为
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.