C++小练习

1.编写一个程序,其中的main()调用一个用户定义的函数(以摄氏温度值为参数,并返回相应的华氏温度值)。该程序下面的格式要求用户输入摄氏温度值,并显示结果:

Please enter a Celsius value: 20
20 degrees Celsius is 68 degrees Fahrenheit.

转换公式:华氏温度=1.8*摄氏温度+32.0

#include<iostream>
using namespace std;
void main()
{
	double Cel;//摄氏温度
	double Fah;//华氏温度
	cout << "Please enter a Celsius value: ";
	cin >> Cel;
	Fah = 1.8 * Cel + 32.0;
	cout << Cel << " degrees Celsius is " << Fah << " degrees Fahrenheit.";
}

2.编写一个程序,其main()调用一个用户定义的函数(以光年值为参数,并返回对应的天文单位的值)。该程序按下面的格式要求用户输入光年值,并显示结果:

Enter the number of light years: 4.2
4.2 light years = 265608 astronomical units.

请使用double类型,转化公式为:1光年=63240天文单位

#include<iostream>
using namespace std;
void main()
{
	double lightyear;
	double astronomical;
	cout << "Enter the number of light years: ";
	cin >> lightyear;
	astronomical = (lightyear / 4.2) * 265608;
	cout << lightyear << " light years = " << astronomical << " astronomical units.";
}

3.编写一个程序,要求用户输入小时数和分钟数。在main()函数中,将这两个值传递给一个void函数,后者以下面的格式显示这两个值:

Enter the number of hours: 9
Enter the number of minutes: 28
Time: 9:28
#include<iostream>
using namespace std;
void Time(int a, int b)
{
	cout << "Time: " << a << ":" << b;
}
void main()
{
	int hour;
	int minute;
	cout << "Enter the number of hours: ";
	cin >> hour;
	cout << "Enter the number of minutes: ";
	cin >> minute;
	Time(hour, minute);
}

思考:题目只要求显示时间数字出来就行,但是如果用户输入的数字有误呢?比如没有34:65这样的时间,所以可以对这个程序进行优化。

#include<iostream>
using namespace std;
void Time(int a, int b)
{
	cout << "Time: " << a << ":" << b;
}
void main()
{
	int hour;
	int minute;
	int i = 1;
	while (i == 1)
	{
		cout << "Enter the number of hours: ";
		cin >> hour;
		cout << "Enter the number of minutes: ";
		cin >> minute;
		if (hour < 0 || hour > 23 || minute < 0 || minute >60)
		{
			cout << "Error! Please enter a valid number." << endl;
		}
		else
		{
			i = 0;//不满足if(),即时间数字在正确范围内时,给i赋值为0,保证能够跳出while循环
		}
	}
	Time(hour, minute);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值