练习1.17:如果输入的所有值都是相等的,本节的程序会输出什么?如果没有重复值,输出又会是怎么样的?
#include <iostream>
int main() {
int currVal = 0, val = 0;
if(std::cin>>currVal){
int cnt = 1;
while (std::cin>>val){
if(val==currVal)
++cnt;
else{
std::cout<<currVal<<" occurs "<<cnt<<" times "<<std::endl;
currVal = val;
cnt=1;
}
}
std::cout<<currVal<<" occurs "<<cnt<<" times "<<std::endl;
}
return 0;
}
输入相同的数据:
12 12 12 12 12 12 12 12 12
输出结果:12 occurs 9 times
输入不相同的数据:
12 13 14 15 16 18 19 20
输出结果:
12 occurs 1 times
13 occurs 1 times14 occurs 1 times
15 occurs 1 times
16 occurs 1 times
18 occurs 1 times
19 occurs 1 times
练习1.18:编译并运行本节的程序,给它输入全部相等的值。再次运行程序,输入没有重复的值。
回答:见上例
练习1.19:修改你为1.4.1节练习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 num1 and num2 : ";
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: 20 30
integers between num1 and num2 : 21 22 23 24 25 26 27 28 29