2013-04-18
1.10 求50到100所有自然数的和
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 int sum = 0; 7 for (int val = 50; val <= 100; ++val) 8 sum += val; 9 cout << sum ; 10 return 0; 11 }
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 int sum = 0,val = 50; 7 while ( val <= 100 ){ 8 sum += val; 9 ++val; 10 } 11 cout << sum; 12 return 0; 13 }
1.11 输出10到0的递减自然数
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 int val=10; 7 while (val >= 0){ 8 cout << val << endl ; 9 --val; 10 } 11 return 0; 12 }
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 for (int val=10; val >= 0; --val){ 7 cout << val << endl ; 8 } 9 return 0; 10 }
1.14 求用户输入的两个数之间的数的和
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 int v1,v2,v3; 7 cin >> v1 >> v2; 8 int lower,upper; 9 if (v1 > v2) { 10 v3 = v1; 11 v1 = v2; 12 v2 = v3; 13 } 14 int sum = 0; 15 for (int val = v1; val <= v2; ++ val ){ 16 sum += val; 17 } 18 cout << sum << endl ; 19 return 0; 20 }
1.16 输出用户输入的两个数中的较大者
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 int v1,v2; 7 cin >> v1 >> v2; 8 if (v1 <= v2) { 9 cout << v2 << endl ; 10 } 11 else { 12 cout << v1 << endl ; 13 } 14 return 0; 15 }
1.17 要求用户输入一组数,输出之中负数的个数
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 int num=0, val; 7 while (cin >> val) 8 if (val < 0) 9 ++num; 10 cout << num << endl ; 11 return 0; 12 }
1.18 用户输入两个数之间每个数写到标准输出
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 int v1, v2, v3; 7 cin >> v1 >> v2; 8 if (v1 > v2){ 9 v3 = v1; 10 v1 = v2; 11 v2 = v3; 12 } 13 for (int val = v1; val <= v2; ++val) 14 cout << val << endl ; 15 return 0; 16 }
1.19 修改上题程序,使每行输出不超过10个数
1 #include<iostream> 2 using namespace std; 3 4 int main() 5 { 6 int v1, v2, v3; 7 cin >> v1 >> v2; 8 if (v1 > v2){ 9 v3 = v1; 10 v1 = v2; 11 v2 = v3; 12 } 13 for (int val = v1; val <= v2;){ 14 for (int i = 1; i <= 10;++i) 15 if (val <= v2) 16 cout << val++ << " "; 17 cout << endl; 18 } 19 return 0; 20 }
1.21