【发布时间】: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;
}
【问题讨论】:
-
为什么需要第二个数组?目标不只是对第一个数组中的元素求和吗?