標籤:
練習1.17 :編寫程式, 要求使用者輸入一組數. 輸出資訊說明其中有多少個負數.
下面的代碼並不完美, 因為只能輸入20個以內的數, 等以後找到解決辦法再修改吧.
1 #include <iostream> 2 3 using namespace std; 4 5 int main() 7 { 8 int array[20] = {0}; 9 int n;10 cout << "請輸入數位個數: " << endl;11 cin >> n;12 cout << "請輸入這些數字: " << endl;13 for (int i = 0; i < n; ++i)14 {15 cin >> array[i];16 }17 18 int sum = 0;19 20 for (int i = 0; i < n; ++i)21 {22 if(array[i] < 0)23 sum++;24 }25 26 cout << "the num of negitive is " << sum << endl;27 return 0;28 }
這裡還有一個方法,也有些不完美:
1 #include <iostream> 2 3 using namespace std; 4 5 6 int main() 7 { 8 9 int sum = 0, value;10 11 while(cin >> value) //只有輸入值不是int 類型值時, 迴圈才會結束12 { //這就需要在你輸入完一組數後,再輸入一個"非法"的數13 if(value < 0) //以結束迴圈14 sum++;15 }16 17 cout << sum << endl;18 return 0;19 }
練習1.19: 提示使用者輸入兩個數, 並將這兩個數範圍的每個數寫到標準輸出, 每一行的輸出不超過10 個數.
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 7 int v1, v2; 8 cout << "please enter two numbers: " << endl; 9 cin >> v1 >> v2;10 11 int lower, upper;12 if (v1 <= v2)13 {14 lower = v1;15 upper = v2;16 }17 else18 {19 lower = v2;20 upper = v1;21 }22 23 for(int i = lower, count = 1; i <= upper; ++i, ++count)24 {25 26 if(count % 10 == 0) 27 {28 cout << i << endl; //每計夠10個數就換行一次.29 30 }31 else32 {33 cout << i << " "; 34 35 }36 37 38 }39 40 41 return 0;42 }
還可以通過重設計數器的方法實現, 但感覺沒有這個簡便:
1 int counter = 0; 2 for(int i = lower; i <= upper; ++i)//只有輸入值不是int 類型值時, 迴圈才會結束 3 { 4 5 if(counter < 10) // 6 { 7 cout << i << " "; 8 9 }10 else11 {12 cout << i << endl;13 counter = 0;14 }15 }
練習1.23 編寫程式, 讀入幾個具有相同ISBN的交易, 輸出所有讀入交易的和.
1 #include <iostream> 2 #include "Sales_item.h" 3 4 using namespace std; 5 6 int main() 7 { 8 Sales_item book1, book2; 9 10 if (cin >> book1) //cin操作符返回的是bool值11 {12 while (cin >> book2)13 {14 if (book1.same_isbn(book2))15 book1 += book2;16 else17 {18 cout << "different ISBN" << endl;19 20 // return -1; //如果執行到這一句, 程式就會結束.21 }22 23 cout << book1 << endl;24 }25 }26 27 28 else29 {30 cerr << "No data ?" << endl;31 32 return -1;33 }34 35 return 0;36 }
讀C++ primer 的一些練習