【问题标题】:Troubleshooting for loop - problems with sum循环故障排除 - sum 问题
【发布时间】:2021-10-11 19:15:27
【问题描述】:

我正在学习 C 编程入门课程,但遇到了 for 循环问题。

我想做两个 double 数组。一种是从用户那里获取输入,另一种是对输入求和。 然后我想输出这两个数组。一个显示输入,一个显示每个单元格中输入的总和。

当我尝试显示数组中每个“单元格”的总和时,问题就出现了。 输出与输入相同。 我可以解决它:

// print all the numbers in the second array
   for (i = 0; i < n; i++) {
     sum = sum + a[i];
       printf("%lf ", sum);

但是任务不会得到解决。希望大家多多指教。

#include <stdio.h> #include <stdlib.h>


int main(void) {

int n; //numbers of cells
int i; //The numbers in the cells


printf("How many cells in the array would you like? \n");
scanf("%d", &n);


double a[n], sum=0; // declare an array and a loop variable.
double b[n], sumo=0;

printf("Enter the numbers:\n");


for (i = 0; i < n; i++) { // read each number from the user
    scanf("%lf", &a[i]);
}

printf("The results, my lord:\n");

// print all the numbers in the first array
for (i = 0; i < n; i++) {
    printf("%lf ", a[i]);

}
printf("\n"); //THIS IS WHERE THE PROBLEM STARTS
// print all the numbers in the second array
   for (i = 0; i < n; i++) {
     b[i] = b[i] + a[i];
       printf("%lf ", b[i]);
   }

return 0;

}

【问题讨论】:

  • 为什么需要第二个数组?目标不只是对第一个数组中的元素求和吗?

标签: c loops for-loop


【解决方案1】:

对于初学者,数组 b 未初始化

double b[n], sumo=0;

所以这个说法

b[i] = b[i] + a[i];

调用未定义的行为。

看来你需要的是下面的for循环

for (i = 0; i < n; i++) {
  b[i] = a[i];
  if ( i != 0 ) b[i] += a[i-1];
    printf("%lf ", b[i]);
}

【讨论】:

  • 感谢您的意见!我试过你的方法,效果很好。然而,我确实以另一种方式解决了它。你可以在评论中看到结果。 :-)
  • b[i] += a[i-1]; --> b[i] += b[i-1]; ?
【解决方案2】:

您可以在读取用户数据时计算总和(又名b 数组):

for (i = 0; i < n; i++) 
{
    scanf("%lf", &a[i]);
    if (i == 0)
    {
        b[i] = a[i];
    }
    else
    {
        b[i] = b[i-1] + a[i];
    }
}

或者这样做:

scanf("%lf", &a[0]);
b[0] = a[0];
for (i = 1; i < n; i++) 
{
    scanf("%lf", &a[i]);
    b[i] = b[i-1] + a[i];
}

或者这样做:

sum = 0;
for (i = 0; i < n; i++) 
{
    scanf("%lf", &a[i]);
    sum += a[i];
    b[i] = sum;
}

【讨论】:

  • 感谢您的意见!我试过你的方法,效果很好。然而,我确实以另一种方式解决了它。你可以在评论中看到结果。 :-)
【解决方案3】:

最后一部分是我如何解决问题的。我发现了这个问题。我没有永远更新“总和”循环。它以这种方式在 b[I] 中添加了一个新值。 :-)

double a[n], sum=0; // declare an array and a loop variable.
double b[n];

printf("Enter the numbers:\n");


for (i = 0; i < n; i++) { // read each number from the user
    scanf("%lf", &a[i]);
}

printf("The results, my lord:\n");

// print all the numbers in the first array
for (i = 0; i < n; i++) {
    printf("%.2lf ", a[i]);

}
printf("\n");
// print all the numbers in the second array
   for (i = 0; i < n; i++) {
     sum = sum + a[i];
     b[i] = sum;
       printf("%.2lf ", b[i]);

【讨论】:

    猜你喜欢
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2013-07-15
    • 2010-11-30
    • 2021-09-11
    • 2012-02-18
    相关资源
    最近更新 更多