数组结对
1.設計思想:測試數組長度的最大范圍,測試每個元素是int32 類型的,將數組的長度設為2,第一個數字輸入最大位數的數字,查看結果。
2.出現的問題:
測試1000個元素,
測試1000個元素程序沒有問題,但是當測試1000000個元素時,程序運行時間過長,時間復雜度過大。
當子數組的和超過最大范圍時,結果為0。
?3.解決方案:1.如果用戶輸入超過最大范圍,提示用戶重新輸入或者計算機拋出異常。
? ? ? ? ? ? ? ? ? 2.將數組定義為長整型的。
? ? ? ? ? ? ? ? ? 3.將結果存入數組。
4.源代碼?
//郭婷 信1305 20132916 2015/3/20 #include<iostream> #include<time.h> using namespace std; #define max(a,b) ((a)>(b)?(a):(b)) int maxsum(int a[], int n) {int i;int maxsofar = 0; //maxsofar記錄到目前為止的的最大值int maxendinghere = 0; //maxendinghere記錄從當前位置開始往前幾個連續的數的和的最大值for (i = 0; i < n; i++){maxendinghere = max(maxendinghere + a[i], 0);maxsofar = max(maxsofar, maxendinghere);}return maxsofar; } int main() {int n, i;cout << "輸入數組的個數:";cin >> n;int *a;a = new int[n];if (a == NULL ){cout << "Error: memory could not be allocated";return 1;}//srand((unsigned)time(NULL));for (i = 0; i < n; i++)cin >> a[i];/*for (i = 0; i < n; i++){a[i] = rand() % 200 - 100;cout << a[i] << " " ;}*/cout << endl;int max=maxsum(a, n);cout << "最大子數組的和為:" << max << endl;delete[]a;return 0; }5.總結
原來寫完一個程序,總覺得運行成功之后就不會有什么錯誤,也沒有更廣、更深的思考,通過這節課的學習,我知道了原來每個程序都有自己所不能涉及的范圍,超過了既定的范圍就會出現錯誤,而這些錯誤往往被我們忽略。所以以后寫程序一定要考慮各種情況,可能出現的各種問題以及解決的問題。
結對伙伴:
郭婷 朱慧敏
轉載于:https://www.cnblogs.com/gting/p/4374908.html
總結
- 上一篇: linux硬盘检测工具,CrazyDis
- 下一篇: css定位:相对定位