概述
练习1.9:编写程序,使用while循环将50到100的整数相加
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int i = 50;
while(i<=100)
{
sum+=i;
i++;
};
cout << "Sum: "<< sum << endl;
return 0;
}
输出结果:
Sum: 3825
Process finished with exit code 0
练习1.10: 除了++运算符将运算对象的值增加1之外,还有一个递减运算符--,实现将值减1。 编写程序,使用递减运算符在循环中按递减顺序打印出10到0之间的整数。
#include <iostream>
using namespace std;
int main() {
int i = 10;
while(i>=0)
{
cout << "i: "<< i << endl;
--i;
};
return 0;
输出结果:
i: 10
i: 9
i: 8
i: 7
i: 6
i: 5
i: 4
i: 3
i: 2
i: 1
i: 0
Process finished with exit code 0
练习1.11: 编写程序,提示用户输入两个整数,打印出这两个整数所指定的范围内的所有整数。
#include <iostream>
using namespace std;
int main() {
int num1,num2;
cout<<"Enter two integers numbers: ";
cin>>num1>>num2;
//search integers between entered two numbers
cout<<"integers between a and b : ";
if (num1<num2)
{
while (num1<num2-1)
{
num1 = num1 + 1;
cout<<num1<<" ";
}
} else
{
while (num1>num2+1)
{
num1 = num1 - 1;
cout<<num1<<" ";
}
}
输出结果:
Enter two integers numbers: 12 9
integers between a and b : 11 10
Process finished with exit code 0
最后
以上就是坚定钢笔为你收集整理的C++Primer(第5版) 1.4.1节练习的全部内容,希望文章能够帮你解决C++Primer(第5版) 1.4.1节练习所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复