[問題] 計算使用者輸入數列之平均值
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
C++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
是這樣的 小弟有個功課是要寫一個讓使用者輸入一個數列
以9999為停止數字 程式將會計算9999之前的數字的平均值
餵入的資料(Input):
10
20
9999
預期的正確結果(Expected Output):
15
錯誤結果(Wrong Output):
-2.94091e+08
程式碼(Code):
// ConsoleApplication3.cpp : 定義主控台應用程式的進入點。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int *number = new int[1];
int arraylength = 0;
int warning_value;
double result = 0;
int main()
{
cout << "請輸入欲計算平均值之數字:";
for (int i = 0; warning_value != 9999; i++ )
{
int *number = new int[i];
cin >> *(number+i);
arraylength = i + 1; //紀錄目前陣列長度
warning_value = number[i];
}
for (int i = 0; i <= arraylength; i++)
if (i != arraylength)
result += number[i];
else
{
result += number[i];
result = result / arraylength;
}
delete[]number;
cout << "計算平均值之結果為:" << result << endl;
system("pause");
}
補充說明(Supplement):
找了很久實在是找不到bug點在哪裡.....
才來po文求助
new 是我翻google找到的 不知道這樣用對不對...
會不會是錯在new? 還是其他地方的錯誤
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.249.32.186
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1460527770.A.8A0.html
→
04/13 14:23, , 1F
04/13 14:23, 1F
→
04/13 14:26, , 2F
04/13 14:26, 2F
→
04/13 14:27, , 3F
04/13 14:27, 3F
→
04/13 14:28, , 4F
04/13 14:28, 4F
→
04/13 14:28, , 5F
04/13 14:28, 5F
→
04/13 14:29, , 6F
04/13 14:29, 6F
→
04/13 14:32, , 7F
04/13 14:32, 7F
→
04/13 14:35, , 8F
04/13 14:35, 8F
→
04/13 15:10, , 9F
04/13 15:10, 9F
→
04/13 15:11, , 10F
04/13 15:11, 10F
推
04/14 01:09, , 11F
04/14 01:09, 11F
→
04/14 01:11, , 12F
04/14 01:11, 12F
→
04/14 01:12, , 13F
04/14 01:12, 13F
→
04/14 01:12, , 14F
04/14 01:12, 14F