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;
}

猜你喜欢

转载自blog.csdn.net/qq_39933320/article/details/89879798