簡體   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