C++primer 第四版部分习题的解答

本文介绍了一个简单的C++程序,演示了如何进行变量的输入、输出以及基本的条件判断。通过实例,展示了如何使用cin和cout进行数据交互,并通过if语句实现基本的逻辑判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.16
#include<iostream>
#include<stdio.h>
using namespace std;
int main(){
    int a, b;
    cout<< "Enter two number "<<endl;
    cin >> a>> b;
    if (a > b)
        cout << "the larger number of a and b is " << a;
    else
        cout << "the lager number of a and b is " << b;

    system("pause");
    //return 0;

}


1.17
#include<iostream>
using namespace std;
int main(){
    int amount = 0, value;
    while (cin>>value)
        if (value <= 0){
            amount ++;
        }
    system("pause");
    return amount;
}
***
这里有一个需要注意的地方是文件结束符的使用。
即cin在什么时候终止的问题。当你在命令行输入多个数之后,在命令行输入ctrl+z之后就可以结束输入。接着程序就会处理你所输入的数字并输出结果。***

1.18
#include<iostream>
using namespace std;
int main(){
    int a, b,s,l,i;
    cin >> a >> b;
    if (a >=b)
        s = b, l = a;
    else
        s = a, l = b;
    for (i = s; i <= l; i++){
        cout << i << " ";
            }
    system("pause");        
}

1.19

#include<iostream>
using namespace std;
int main(){
    int a, b, lower,upper, i;
    cin >> a >> b;
    if (a >= b)
        lower = b, upper = a;
    else
        lower = a, upper = b;
    int amount=0;
    for (i = lower; i <= upper; i++){
            cout << i << " "  ;
            amount++;
            if (amount % 10 == 0)
                cout << endl;
        }
    system("pause");        
}

1.20
#include<iostream>
using namespace std;
int main(){
    int a, b,lower,upper;
    int i,sum = 0;
    cin >> a>> b;
    if (a > b)
        lower = b, upper = a;
    else
        lower = a, upper = b;
    for (i = lower; i <= upper; i++)
    {
        sum += i;
    }
    cout << "The sum between a and b is " << sum << endl;
    system("pause");

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值