简体   繁体   English

使用C中的数组进行扫描和求和

[英]Scan and sum using array in C

I'm trying to write a simple program that'll prompt the user to enter N numbers, store them in an array, then just sum them all up 我正在尝试编写一个简单的程序,该程序将提示用户输入N个数字,将它们存储在数组中,然后将它们全部求和

I understand I can just do this with a recursion but I'm trying to learn how array works 我知道我可以通过递归来做到这一点,但我正在尝试学习数组的工作原理

Example: 例:

1 (hit enter) 2 (hit enter) ... 10 (hit enter) 1(命中输入)2(命中输入)... 10(命中输入)

Expected output: 55 预期产量:55

#include <stdio.h>

int main (void){
  int n;
  int a[n];
  int counter;

  printf("How many numbers do you want to enter? \n");
  scanf("%d", &n);

  printf("OK! now enter your number: \n");
  for (int i = 0; i <= n; i++){
    scanf("%d", &a[i]);
    counter =+ a[i];
  }

  printf("The answer is: %d\n", counter);
  return 0;
} 

Right now there's no error message, no output, just the standard windows error message "scanner.exe has stopped working..." 现在没有错误消息,没有输出,只有标准的Windows错误消息“ scanner.exe已停止工作...”

I'm using Win8 and GCC compiler 我正在使用Win8和GCC编译器

First of all, you can't create an static array without first knowing its size. 首先,您必须先知道其大小才能创建静态数组。 You first need to ask the user for the "n" variable and then declare your array. 您首先需要向用户询问“ n”变量,然后声明您的数组。

You also need to explicitly initialize your counter variable to be zero before you start counting. 在开始计数之前,还需要将计数器变量显式初始化为零。 In C, variables don't default to 0 when you declare them. 在C语言中,变量在声明时不会默认为0。

The operator "=+" doesn't exist AKAIK, change it to "+=". 运算符“ = +”不存在,不会更改为“ + =”。

Last but not least, the limit in your loops is a little off, you're asking for 11 values ;) (I edited this post, I was wrong about only asking for 9 values. I tend to confuse that sort of stuff) 最后但并非最不重要的一点是,循环的极限有点小,您要的是11个值;)(我编辑了这篇文章,我只问了9个值是错误的。我倾向于混淆这种东西)

#include <stdio.h>

int main (void){
  int n;
  int counter = 0;

  printf("How many numbers do you want to enter? \n");
  scanf("%d", &n);

  int a[n];

  printf("OK! now enter your number: \n");
  for (int i = 0; i < n; i++){
    scanf("%d", &a[i]);
    counter += a[i];
  }

  printf("The answer is: %d\n", counter);
  return 0;
}

You are using variable length arrays. 您正在使用可变长度数组。 At run time the value of n must be known. 在运行时,必须知道n的值。 Place the declaration 放置声明

int a[n];  

after taking input for n , ie, after scanf("%d", &n); 在输入n ,即在scanf("%d", &n); and initialize counter to zero before using it otherwise you will get garbage value (because of undefined behavior). 并在使用counter之前将counter初始化为零,否则将获得垃圾值(由于未定义的行为)。
Also change the for loop condition from i <= n to i < n . 还将for循环条件从i <= n更改为i < n

After this line: 在此行之后:

int n;

What do you think the value of n is? 您认为n的值是什么?

Now go to the next line: 现在转到下一行:

int a[n];   

How big is this array? 这个数组有多大?
Can you access it properly? 您可以正确访问吗?

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

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