《151道题带你快速梳理C++知识(3)-- 条件判断与循环(上)》

🔥小龙报:个人主页
🎬作者简介:C++研发,嵌入式,机器人方向学习者
❄️个人专栏:《C语言》《算法》KelpBar海带Linux智慧屏项目
✨永远相信美好的事情即将发生

前言
本专栏聚焦算法题实战,系统讲解算法模块:以《c++编程》,《数据结构和算法》《基础算法》《算法实战》 等几个板块以题带点,讲解思路与代码实现,帮助大家快速提升代码能力
ps:本章节题目分两部分,比较基础笔者只附上代码供大家参考,其他的笔者会附上自己的思考和讲解,希望和大家一起努力见证自己的算法成长
一、整除判断
1.1题目链接:整除判断
1.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
int m,n;
cin >> m >> n;
if(m % n == 0)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
二、整数大小比较
2.1题目链接:整数大小比较
2.2题目解析

c
#include <iostream>
using namespace std;
int main()
{
long long x,y;
cin >> x >> y;
if(x == y)
cout << "=";
else if(x < y)
cout << "<";
else if(x > y)
cout << ">";
return 0;
}
三、输出绝对值
3.1题目链接:输出绝对值
3.2题目解析

代码:
c
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
double n;
cin >> n;
if(n >= 0)
printf("%.2lf",n);
else
printf("%.2lf",fabs(n));
return 0;
}
四、奇偶数判断
4.1题目链接:奇偶数判断
4.2题目解析

c
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
if(n % 2 == 0)
cout << "even";
else
cout << "odd";
return 0;
}
五、有一门课不及格的学生
5.1题目链接:有一门课不及格的学生
5.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
int cnt = 0;
for(int i = 0;i < 3;i++)
{
int x;
cin >> x;
if(x < 60)
cnt++;
}
if(cnt == 1)
printf("1");
else
printf("0");
return 0;
}
六、 最大数输出
6.1题目链接:最大数输出
6.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
cin >> a >> b >> c;
int max = (a > b ? a : b);
if(max < c)
{
max = c;
cout << c << endl;
}
else
cout << max << endl;
return 0;
}
七、 等差数列末项计算
7.1题目链接:等差数列末项计算
7.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
int a1, a2, n;
cin >> a1 >> a2 >> n;
cout << a1 + (n - 1) * (a2 - a1) << endl;
return 0;
}
八、特殊计算
8.1题目链接:特殊计算
8.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
long long x,y,z;
cin >> x >> y;
if(y % x == 0)
z = x+ y;
else
z = y - x;
cout << z << endl;
return 0;
}
九、Apples Prologue / 苹果和虫子
9.1题目链接:Apples Prologue / 苹果和虫子
9.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
int m, t, s;
cin >> m >> t >> s;
if (t == 0)
{
cout << 0 << endl;
return 0;
}
if (s % t == 0) //情况一:t = 0;
{
cout << ((m - (s / t) > 0) ? (m - (s / t)) : 0) ;
}
else
cout << ((m - (s / t) - 1 > 0) ? (m - (s / t) - 1): 0);
return 0;
}
注意:
这道题有三个陷进:1.t 即除数可能为零
2.苹果可能在规定时间内吃完也为0
十、闰年判断
10.1题目链接:闰年判断
10.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
int y;
cin >> y;
if ((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0))
cout << 1 << endl;
else
cout << 0 << endl;
return 0;
}