#include<iostream> intmain() { int sum = 0, val = 50; while (val <= 100) { sum += val; ++val; } std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl; return0; }
练习1.10
1 2 3 4 5 6 7 8 9 10 11 12
#include<iostream> intmain() { int sum = 0, val = 10; while (val >= 0) { sum += val; --val; } std::cout << "Sum of 0 to 10 inclusive is " << sum << std::endl; return0; }
练习1.11(以下代码满足练习1.19的要求)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream> intmain() { int a, b, c = 0; std::cout << "Enter two numbers" << std::endl; std::cin >> a >> b; if (a > b) { c = a; a = b; b = c; } while (b >= a) { std::cout << a << " "; ++a; } return0; }
练习1.12 程序的功能是求[-100, 100]范围内的整数的和,sum的终值为0
1 2 3 4 5 6 7 8 9
#include<iostream> intmain() { int sum = 0; for (int i = -100; i <= 100; ++i) sum += i; std::cout << sum << std::endl; return0; }
#include<iostream> intmain() { int sum = 0; int a, b, c = 0; for (int i = 50; i <= 100; ++i) sum += i; std::cout << "The sum of 50 to 100 is " << sum << std::endl; for (int j = 10; j >= 0; --j) { std::cout << j << " "; if (j == 0) std::cout << std::endl; } std::cout << "Enter two numbers" << std::endl; std::cin >> a >> b; if (a > b) { c = a; a = b; b = c; } for (; a <= b; ++a) std::cout << a << " "; return0; }
练习1.14
已知循环次数的时候用for简便,未知时用while简便
练习1.16
文件结束符(Windows系统为Ctrl+Z,然后按Enter)
1 2 3 4 5 6 7 8 9
#include<iostream> intmain() { int sum = 0, value = 0; while (std::cin >> value) sum += value; std::cout << "Sum is " << sum << std::endl; return0; }