c++ primer plus 第二章编程题

第二章

1 显示姓名和地址

#include <iostream>
using namespace std;
int main()
{
    cout << "小明" << ' ' <<  "来自中国" << endl;
}

2 输入以long为单位的距离,转换为码(一long等于220码

#include <iostream>
using namespace std;
int convert(int a)
{
    return a * 220;
}
int main()
{
    cout << "输入一个距离" << endl;
    int l = 0;
    cin >> l;
    cout << l << " long " << "equals to " << convert(l) << " 码" << endl;
}

3 使用3个用户定义的函数输出四句诗

#include <iostream>
using namespace std;

void out_1()
{
    cout << "Three blind mice" << endl;
}

void out_2()
{
    cout << "See how they run" << endl;
}
int main()
{
    out_1();out_1();out_2();out_2();
    return 0;
}

4 输入年龄,输出包含几个月

#include <iostream>
using namespace std;

int out_month(int input_age)
{
    return input_age * 12;
}

int main()
{
    cout <<"Enter your age: " << endl;
    int age;
    cin >> age;
    cout << "Your age contains " << out_month(age) << " months"<< endl;
    return 0;
}

5 调用一个自定函数完成摄氏度转换

#include <iostream>
using namespace std;

double convert(double input_degree)
{
    return (input_degree * 1.8) + 32.0;
}

int main()
{
    cout <<"Enter a degree Celsius: " << endl;
    double degreeC;
    cin >> degreeC;
    cout << degreeC << " degree Celsius equals to " << 
            convert(degreeC) << " degree Fahrenheit"<< endl;
    return 0;
}

6 编写自定义函数完成天文单位的转换

#include <iostream>
using namespace std;

double convert(double input_lightYears)
{
    return input_lightYears * 63240;
}

int main()
{
    cout <<"Enter a number of light years: " << endl;
    double lightyears;
    cin >> lightyears;
    cout << lightyears << " light years equals to " <<
            convert(lightyears) << " astronomical units"<< endl;
    return 0;
}

7 合并显示小时数和分钟数

#include <iostream>
using namespace std;

//用来合并两个数的函数
void merge(int hour, int minute)
{
    cout << hour << ':' << minute << endl;
}

//用来判断小时和分钟数是否有效的函数
bool isValid_hour(int input_hour = 0)
{
    return (0 <= input_hour && input_hour < 24);
}

bool isValid_minute(int input_minuete = 0)
{
    return (0 <= input_minuete && input_minuete < 60);
}

int main()
{
    int hour,minute;

    cout <<"Enter a number of hour: " << endl;
    cin >> hour;
    cout <<"Enter a number of minute: " << endl;
    cin >> minute;

    if(isValid_hour(hour) && isValid_minute(minute))
        merge(hour,minute);
    else
        if (!isValid_hour(hour))
            cout << "Invalid input of hour!" << endl;
        if (!isValid_minute(minute))
            cout << "Invalid input of minute!" << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冻羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值