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

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

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

代码:
c
#include <iostream>
using namespace std;
typedef long long LL;
LL m,k;
int main()
{
cin >> m >> k;
int ret = 0;
while (m)
{
if (m % 10 == 3)
ret++;
m /= 10;
}
if (ret == k)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
二、角谷猜想
2.1题目链接 : 角谷猜想
2.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
long long n;
scanf("%lld", &n);
while (n != 1)
{
if (n % 2 != 0)
{
printf("%lld*3+1=%lld\n", n,n * 3 + 1);
n = n * 3 + 1;
}
else if(n % 2 == 0)
{
printf("%lld/2=%lld\n", n, n / 2);
n /= 2;
}
}
printf("End\n");
return 0;
}
三、计算1~100之间3的倍数的数字之和
3.1题目链接:无
3.2题目解析
法一:
c
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
for (int i = 1; i <= 100; i++)
{
if (i % 3 == 0)
sum += i;
}
cout << sum << endl;
return 0;
}
法二:
c
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
for (int i = 3; i <= 100; i += 3)
sum += i;
cout << sum << endl;
return 0;
}
四、平均年龄
4.1题目链接:平均年龄
4.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int sum = 0;
for (int i = 1; i <= n; i++)
{
int x;
cin >> x;
sum += x;
}
double ret = sum * 1.0 / n;
printf("%.2lf", ret);
return 0;
}
五、奥运奖牌计数
5.1题目链接:奥运奖牌计数
5.2题目解析

代码:
c
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int a,b,c;
int sum_a = 0;
int sum_b = 0;
int sum_c = 0;
int sum = 0;
for(int i = 0;i < n;i++)
{
cin >> a >> b >> c;
sum_a += a;
sum_b += b;
sum_c += c;
}
sum = sum_a + sum_b + sum_c;
cout << sum_a << " " << sum_b << " " << sum_c << " " << sum;
return 0;
}
六、鸡尾酒疗法
6.1题目链接:鸡尾酒疗法
6.2题目解析

代码:
c
#include <iostream>
using namespace std;
int n;
int main()
{
cin >> n;
int a,b;
cin >> a >> b;
double x = (b * 1.0 / a) * 100;
for (int i = 1; i < n; i++)
{
cin >> a >> b;
double y = (b * 1.0 / a) * 100;
if (y - x > 5)
cout << "better" << endl;
else if (x - y > 5)
cout << "worse" << endl;
else
cout << "same" << endl;
}
return 0;
}
注:这道题要把握住两个相差,第二个if也可以使用绝对值函数abs(y - x)不能直接y - x否则会造成same和worse两个的判度的逻辑错误
七、计算分数加减表达式的值
7.1题目链接:计算分数加减表达式的值
7.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
double s = 0;
int fact = 1;
for (int i = 1; i <= n; i++)
{
s += 1.0 / i * fact;
fact *= -1;
}
printf("%.4lf", s);
return 0;
}
八、求分数序列和
8.1题目链接:求分数序列和
8.2题目解析

代码:
c
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int p = 1;
int q = 2;
double sum = 0;
for (int i = 1; i <= n; i++)
{
sum += (q * 1.0/ p);
q = q + p;
p = q - p;
}
printf("%.4lf", sum);
return 0;
}
九、输入个正整数,计算这个整数是⼏位数
9.1题目链接:无
9.2题目解析
c
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int ans = 0;
do
{
ans++;
n /= 10;
} while (n);
cout << ans << endl;
return 0;
}
总结 ---- 每日励志时刻
