[英]calculating the sum of input numbers in c language
我想使用 c 語言中的指針概念計算輸入數字的總和。但是當我編譯下面給出的程序時,不會出現 sum 的正確值。 幫我找出我在下面的程序中犯的錯誤。
#include<stdio.h>
void main()
{
int g , *p;
int sum = 0;
int x=1;
for(int i=1; i<3; i++ )
{
scanf("%d ", &g);
}
p = &g;
while( x < 3){
sum = sum + *p;
p++;
x++;
}
printf("\n sum = %d ",sum);
}
你的g
只有一個integer 所以:
scanf("%d ", &g);
,您將覆蓋以前的值。p++;
,該指針將不再有效。 (你認為它會指向哪里?) 如果要在g
中存儲三個不同的值,則需要將其設為整數數組。
為此,請對您的代碼進行以下更改:
int g[3] , *p; // "g" can now store three different values
int x=0; // Later on - counting from 0 thru 2 in the "while" loop
//...
for (int i=0; i<3; i++) // NOTE: Arrays begin at "0" in C!
{
scanf("%d ", &g[i]); // Store to the element indexed by "i"
}
//...
p = g; // For arrays, don't need the & operator: this will give address of first element
您只能在g
中存儲一個數字。
因此, p++;
這里會使p
指向一個無效的地方。
您應該分配一個數組來存儲所有輸入值。
另請注意,您應該在托管環境中使用標准int main(void)
而不是void main()
,這在 C89 中是非法的,在 C99 或更高版本中是實現定義的,除非您有特殊原因使用非標准簽名。
#include<stdio.h>
int main(void)
{
int g[3] , *p;
int sum = 0;
int x=1;
for(int i=1; i<3; i++ )
{
scanf("%d ", &g[i]);
}
p = &g[1];
while( x < 3){
sum = sum + *p;
p++;
x++;
}
printf("\n sum = %d ",sum);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.