第一题
这个题目之前描述出错了哈,要求的是于y轴交点的纵坐标。这个其实就是计算
y
=
k
∗
x
+
b
y=k*x+b
y=k∗x+b
中的那个b,那么直接利用公式计算就好,稍微注意下当k不存在的情况即可
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double x1,y1,x2,y2;
cin >>x1>>y1>>x2>>y2;
if( x1 == x2)
{
cout <<"截距不存在";
}
else
{
double k = (y2-y1)/(x2-x1);
double ret = y1 - k * x1;
cout <<fixed<<setprecision(5)<<ret;
}
return 0;
}
第二题
这个其实依据题目的要求分别给出判断即可
#include <iostream>
using namespace std;
int main(){
int a , b;
cin >>a>>b;
int ret = a+b;
if(a > b)
{
ret = a-b;
}
else if(a == b)
{
ret = a * a;
}
cout << ret;
return 0;
}
第三题
这个算法其实再执行一次的话就是把加密的数字还原了,不知道同学注意到没有,其他方面主要注意的点有两个
1.除以符号运算得到的结果是一个小数,需要时刻提醒自己
2.取余符号需要符号两边都是整数才能计算,针对浮点数的取余操作要调用另一个头文件cmath
里面的函数才能做到,另外取余这种东西有多种取余方式,有向0靠近的取余,也有向正/负无穷靠近的取余,计算机中的到底是哪种同学们也可以自己测试一下
#include <iostream>
using namespace std;
int main(void) {
int num = 0;
cin >> num;
int one = (num+5)%10;
int ten = (num/10+5)%10;
int hun=(num/100+5)%10;
int tho=(num/1000+5)%10;
int ret=0;
ret+=tho;
ret+= hun*10;
ret+= ten*100;
ret+= one*1000;
cout <<setw(4)<<setfill('0')<< ret;
return 0;
}
第四题
这个主要是注意下浮点数的精度问题,倘若用float,很多同学在其中一个测试集合里面会得出一个有5位小数的结果,实际上正确答案只有三位小数,但是代码看上去也没问题呀?原因就是float的精度不够,涉及到这个浮点数之间相乘的时候往往会出现误差,这个时候最好使用double类型来做
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
double x1,y1,x2,y2;
cin >>x1>>y1>>x2>>y2;
double wid = fabs(x1 - x2);
double len = fabs(y1 - y2);
double ret = wid * len;
if(ret == 0)
{
cout << "不存在对应的矩形";
}
else
{
cout <<fixed<<setprecision(5)<<ret<<" ";
if (wid == len)
{
cout <<"是正方形";
}
else
{
cout <<"不是正方形";
}
}
return 0;
}
第五题
这个题目出现很多次了吧,其实就是相当于求天数,然后对5进行取余,类似的思路在之前的博客中已经提到多次了,后面还会有一次类似的题目帮助同学们理解到底为什么要出现循环和数组这两种东西帮助写代码
#include <iostream>
using namespace std;
int main()
{
int year, month, day, num;
cin >> year >> month >> day;
/* 计算因为年份多出来的天数 */
for (int i = 1990; i <= year - 1; i++) {
day += 365;
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {
day += 1; // 闰年多加1天
}
}
/* 计算因为月份多出来的天数 */
for (int i = 1; i <= month - 1; i++) {
if (i == 2) {
day += 28; // 平年2月有28天
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
day += 1; // 闰年2月多加一天
}
} else if (i == 4 || i == 6 || i == 9 || i == 11) {
day += 30; // 4 6 9 11月份
} else {
day += 31; // 其他月份 即1 3 5 7 8 10 12
}
}
num = (day - 1) % 5 + 1; // 得出1 2 3 4 5之间的数,而不是 0 1 2 3 4
if (num >= 4) {
cout << "Sleeping"; // 后两天晒网
} else {
cout << "Fishing"; // 前三天打鱼
}
// /* 另一种方式 */
// num = day % 5; // 得出 0 1 2 3 4, 0相当于第5天
// if (num == 4 || num == 0) {
// cout << "Sleeping";
// } else {
// cout << "Fishing";
// }
return 0;
}