7 条题解
-
2
这道题的思路比较简单,可以使用循环和条件语句来实现。具体流程如下:
- 输入一个正整数 n。
- 如果 n 等于 1,则输出 end,结束程序。
- 否则,判断 n 是否为偶数:
- 如果是偶数,则将 n 除以 2,并输出当前结果。
- 如果是奇数,则将 n 乘以 3 再加 1,并输出当前结果。
- 回到第 2 步。
以下是详细的代码注释:
#include <iostream> using namespace std; int main() { int n; cin >> n; // 输入正整数 n while (n != 1) { // 当 n 不等于 1 时执行循环 cout << n; // 输出当前值 if (n % 2 == 0) { // 如果 n 是偶数 cout << "/2="; // 输出运算符 n /= 2; // 将 n 除以 2 } else { // 如果 n 是奇数 cout << "*3+1="; // 输出运算符 n = n * 3 + 1; // 将 n 乘以 3 再加 1 } cout << n << endl; // 输出计算后的结果 } cout << "End" << endl; // 输出结束语句 return 0; }
- 1
信息
- ID
- 182
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 1
- 标签
- 递交数
- 132
- 已通过
- 97
- 上传者