Re: [問題] 怎麼用C寫出move average ?
// Provide output capability.
#include <iostream>
using std::cout;
using std::endl;
/* MAIN PROGRAM */
int main() {
// Initialize variables.
const int NUMBERS_SIZE = 10;
double numbers[NUMBERS_SIZE] = {1.0, 2.0, 3.0, 4.0, 5.0,
6.0, 7.0, 8.0, 9.0, 10.0};
int windowSize = 4;
double sum = 0.0;
double movingAverage = 0.0;
// Loop through nums in list, excluding any at the end that will be
//+ covered by the nested for-loop.
for (int i = 0; i <= (NUMBERS_SIZE - windowSize); i++) {
sum = 0.0; // Reinitialize sum back to zero.
cout << "For numbers "; // Output message.
// Loop through x numbers from current i position, where x = windowSize.
for (int j = i; j < i + windowSize; j++) {
sum += numbers[j]; // Increment sum.
cout << numbers[j] << " "; // Display the currently addressed num.
}
// Calculate moving average and display.
movingAverage = sum / windowSize;
cout << endl << "Moving Average: " << movingAverage << endl << endl;
}
return 0;
}
上面是C++的打法!! 但我需要C的打法不知道怎麼打
會像下面這樣
The output looks like
For numbers 1 2 3 4
Moving Average: 2.5
For numbers 2 3 4 5
Moving Average: 3.5
For numbers 3 4 5 6
Moving Average: 4.5
For numbers 4 5 6 7
Moving Average: 5.5
For numbers 5 6 7 8
Moving Average: 6.5
For numbers 6 7 8 9
Moving Average: 7.5
For numbers 7 8 9 10
Moving Average: 8.5
希望有人能幫小弟一下,謝謝大家
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.38.82.110
→
05/31 10:56, , 1F
05/31 10:56, 1F
→
05/31 11:41, , 2F
05/31 11:41, 2F
→
05/31 12:48, , 3F
05/31 12:48, 3F
→
05/31 12:50, , 4F
05/31 12:50, 4F
→
05/31 13:01, , 5F
05/31 13:01, 5F
→
05/31 13:14, , 6F
05/31 13:14, 6F
→
05/31 13:15, , 7F
05/31 13:15, 7F
噓
05/31 13:17, , 8F
05/31 13:17, 8F
噓
05/31 13:21, , 9F
05/31 13:21, 9F
→
05/31 13:21, , 10F
05/31 13:21, 10F
噓
05/31 13:22, , 11F
05/31 13:22, 11F
→
05/31 13:23, , 12F
05/31 13:23, 12F
→
05/31 13:23, , 13F
05/31 13:23, 13F
噓
05/31 13:26, , 14F
05/31 13:26, 14F
→
05/31 13:31, , 15F
05/31 13:31, 15F
→
05/31 13:32, , 16F
05/31 13:32, 16F
→
05/31 13:33, , 17F
05/31 13:33, 17F
噓
05/31 13:33, , 18F
05/31 13:33, 18F
→
05/31 13:35, , 19F
05/31 13:35, 19F
→
05/31 13:35, , 20F
05/31 13:35, 20F
噓
05/31 13:36, , 21F
05/31 13:36, 21F
→
05/31 13:36, , 22F
05/31 13:36, 22F
→
05/31 13:38, , 23F
05/31 13:38, 23F
→
05/31 13:39, , 24F
05/31 13:39, 24F
噓
05/31 13:42, , 25F
05/31 13:42, 25F
噓
05/31 13:47, , 26F
05/31 13:47, 26F
→
05/31 13:49, , 27F
05/31 13:49, 27F
→
05/31 13:50, , 28F
05/31 13:50, 28F
→
05/31 13:54, , 29F
05/31 13:54, 29F
→
05/31 13:54, , 30F
05/31 13:54, 30F
→
05/31 14:17, , 31F
05/31 14:17, 31F
→
05/31 14:31, , 32F
05/31 14:31, 32F
→
05/31 14:35, , 33F
05/31 14:35, 33F
推
05/31 16:28, , 34F
05/31 16:28, 34F
→
05/31 18:57, , 35F
05/31 18:57, 35F
→
05/31 19:23, , 36F
05/31 19:23, 36F
→
06/01 13:53, , 37F
06/01 13:53, 37F
→
06/01 15:15, , 38F
06/01 15:15, 38F
→
06/01 23:45, , 39F
06/01 23:45, 39F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章