C++语言版实现代码
习题1-1 平均数(average)
输入3个整数,输出它们的平均值,保留3位小数。
#include "pch.h"
#include
#include
#include
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b >> c;
cout.setf(ios::fixed);
cout << setprecision(3) << (a + b + c) / 3.000 << endl;
return 0;
}
习题1-2 温度(temperature)
输入华氏温度f,输出对应的摄氏温度c,保留3位小数。提示:c=5(f-32)/9。
#include "pch.h"
#include
#include
#include
using namespace std;
int main()
{
float f, c;
cin >> f;
c = 5.0*(f - 32) / 9;
cout.setf(ios::fixed);
cout << setprecision(3) << c << endl;
return 0;
}
习题1-3 连续和(sum)
输入正整数n,输出1+2+…+n的值。提示:目标是解决问题,而不是练习编程。
#include "pch.h"
#include
#include
#include
using namespace std;
int main()
{
int n;
cin >> n;
double s = n * (1 + n) / 2;
cout << s << endl;
return 0;
}
习题1-4 正弦和余弦(sin和cos)
输入正整数n(n<360),输出n度的正弦、余弦函数值。提示:使用数学函数。
#include "pch.h"
#include
#include
#include
using namespace std;
int main()
{
const double pi = acos(-1.0);
float n;
cin >> n;
cout << sin(n/180*pi) << endl;
cout << cos(n/180*pi) << endl;
return 0;
}
习题1-5 打折 (discount)
一件衣服95元,若消费满300元,可打八五折。输入购买衣服件数,输出需要支付的金 额(单位:元),保留两位小数。
#include "pch.h"
#include
#include
#include
using namespace std;
int main()
{
const int price = 95;
int number;
double total, sum;
cin >> number;
sum = price * number;
if (sum >= 300)
total = sum * 0.85;
else
total = sum;
cout << setprecision(2) << total << "元" << endl;
return 0;
}
习题1-6 三角形(triangle)
输入三角形3条边的长度值(均为正整数),判断是否能为直角三角形的3个边长。如果 可以,则输出yes,如果不能,则输出no。如果根本无法构成三角形,则输出not a triangle。
#include "pch.h"
#include
#include
#include
using namespace std;
int main()
{
int a, b, c, t;
cin >> a >> b >> c;
if (a > b) {
t = a;
a = b;
b = t;
}
if (a > c) {
t = a;
a = c;
c = t;
}
if (b > c) {
t = b;
b = c;
c = b;
}
if (a + b > c && c - b < a)
if (a * a + b * b == c * c)
cout << "yes" << endl;
else
cout << "no" << endl;
else
cout << "not a triangle" << endl;
return 0;
}
习题1-7 年份(year)
输入年份,判断是否为闰年。如果是,则输出yes,否则输出no。
提示:简单地判断除以4的余数是不够的。
#include "pch.h"
#include
#include
#include
using namespace std;
int main()
{
int year;
cin >> year;
if (year % 4 == 0 && year % 100 != 0)
cout << "yes" << endl;
else if (year % 400 == 0)
cout << "yes" << endl;
else
cout << "no" << endl;
return 0;
}