简体   繁体   English

计算 c 语言中输入数字的总和

[英]calculating the sum of input numbers in c language

I want to calculate the sum of input numbers using pointer concept in c language.But when i compile the given below program correct value for sum does not appear.我想使用 c 语言中的指针概念计算输入数字的总和。但是当我编译下面给出的程序时,不会出现 sum 的正确值。 help me to find the mistake i have done in the below program.帮我找出我在下面的程序中犯的错误。

#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);

}

Your g is only one integer so:你的g只有一个integer 所以:

  1. Each time you call scanf("%d ", &g);每次调用scanf("%d ", &g); , you will overwrite the previous value. ,您将覆盖以前的值。
  2. When you increment the pointer in p++;当您在p++; , that pointer will no longer be valid. ,该指针将不再有效。 (Where do you think it will point to?) (你认为它会指向哪里?)

If you want to store three different values in g , you need to make it an array of integers.如果要在g中存储三个不同的值,则需要将其设为整数数组

To do this, make the following changes to your code:为此,请对您的代码进行以下更改:

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

You can store only one number in g .您只能在g中存储一个数字。

Therefore, p++;因此, p++; here will make p point at an invalid place.这里会使p指向一个无效的地方。

You should allocate an array to store all input values.您应该分配一个数组来存储所有输入值。

Also note that you should use standard int main(void) in hosted environment instead of void main() , which is illegal in C89 and implementation-defined in C99 or later, unless you have some special reason to use non-standard signature.另请注意,您应该在托管环境中使用标准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.

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