1.4.1书上例题
#include <iostream>
int main()
{
int sum = 0, val = 1;
while (val <= 10)
{
sum += val;
val++;
}
std::cout << "sum of" << sum << std::endl;
return 0;
}
i++,先运行i,在运行i+1 ; ++i,直接运行i+1
while语句形式
while(condition)
{
statement
}
练习1.9
编写程序,使用while循环将50到100的整数相加
答:
#include <iostream>
int main()
{
int sum = 0, val = 50;
while (val <= 100)
{
sum += val;
val++;
}
std::cout << "sum of 50 to 100 inclusive is " << sum << std::endl;
return 0;
}
练习1.10
使用递减运算符在循环中按递减顺序打印出10到0之间的整数。
答:每次while循环都输出一个数,在循环中打印,先减去1再输出。
#include <iostream>
int main()
{
int a= 10;
std::cout << "0 到10之间的数为 " << std::endl;
while (a >= 1)
{
--a;
std::cout << a << std::endl;
}
return 0;
}
练习1.11
编写程序,提示用户输入两个整数,打印出两个整数所指定的范围内的所有整数。
答:
#include <iostream>
int main()
{
int a= 0,b=0;
std::cin >> a >> b;
std::cout << "输入两个数字 " <<a<<b<< std::endl;
while (a>=b)//从大到小输出
{
std::cout << a << std::endl;
a--;
}
while (a <b)//从小到大输出
{
std::cout << a << std::endl;
a++;
}
return 0;
}
输出结果为ab和ab之间的整数 或者a和ab之间的数。
第二个while如果也有等号的话,会出现重复的a
思考改进:题目存在歧义,选择只出现ab之间的整数(掐头去尾)并且两个while输出不重复。
方案:加入if选择语句,根据调试结果增减b值
#include <iostream>
int main()
{
int a= 0,b=0;
std::cin >> a >> b;
std::cout << "输入两个数字 " <<a<<b<< std::endl;
if(a>b)
while (a>b+1)//从大到小输出
{
--a;
std::cout << a << std::endl;
}
else
while (a <b-1)//从小到大输出
{
a++;
std::cout << a << std::endl;
}
return 0;
}
运行结果