我參加了 C 編程入門課程,并且在 for 回圈方面遇到了問題。
我想做兩個雙陣列。一種從用戶那里獲取輸入,另一種對輸入求和。然后我想輸出兩個陣列。一個顯示輸入,一個顯示每個單元格中輸入的總和。
當我嘗試顯示陣列中每個“單元格”的總和時,問題就出現了。輸出只是變得與輸入相同。我可以解決它:
// 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;
}
uj5u.com熱心網友回復:
對于初學者,陣列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]);
}
uj5u.com熱心網友回復:
您可以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;
}
uj5u.com熱心網友回復:
最后一部分是我如何解決這個問題。我發現了這個問題。我沒有更新永遠回圈的“總和”。它以這種方式在 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]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315531.html
