#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;
#include<iostream> intmain() { int a=0,val=10; while (val>=0) { a=val; --val; std::cout<<a<<std::endl; } return0; }
练习1.11
编写程序,提示用户输入两个整数,打印出这两个整数所指定的范围内的所有整数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include<iostream> intmain() { int a=0,b=0; std::cout<<"please input two numbers:"<<std::endl; std::cin>>a>>b; int min = std::min(a,b); int max = std::max(a,b); while (max>=min) { std::cout<<max<<std::endl; max--; } return0; }
练习1.12
下面的for循环完成了什么功能?sum的终值是多少?
1 2 3
int sum = 0; for (int i = -100; i <= 100; ++i) sum += i;
功能是将从-100到100之间的所有整数累加到变量sum中,sum 的终值为 0。
练习1.13
使用for循环重做1.4.1节中的所有练习(第11页)。
exercise1.9:
1 2 3 4 5 6 7 8 9 10
#include<iostream> intmain() { int sum = 0; for (int i = 50; i <= 100; ++i) {sum += i; } std::cout << "the sum is: " << sum << std::endl; return0; }
exercise1.10:
1 2 3 4 5 6 7 8 9 10
#include<iostream> intmain() { for ( int i = 10; i >= 0; --i) { std::cout<<i<<std::endl; } return0; }
exercise1.11:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<iostream> intmain() { int a=0,b=0; std::cout<<"please input two numbers:"<<std::endl; std::cin>>a>>b; int min = std::min(a,b); int max = std::max(a,b); for (int i = max; i >= min; i--) { std::cout<<i<<std::endl; } return0; }
#include<iostream> intmain() { int sum = 0, value = 0; //读取数据直到文件尾,计算所有读入的值的和 while (std::cin >> value) { sum += value;//等价于sum=sum+value } std::cout <<"Sum is"<< sum << std::endl; return0; }