C++Primer(第5版) 1.4.4节练习

练习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 times 
14 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 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值