pat乙级1001害死人不偿命的(3n+1)猜想 ,不知道错误点在哪里

测试结果如下:
img
代码如下:

#include<iostream>
using namespace std;
int main()
{
    int n = 0, cnt = 0;
    cin >> n;
    if (n <= 0 || n > 1000)
        cout << "wrong" << endl;
    else {
        if (n == 1)
            cout << cnt+1 << endl;
        else {

            for (int i = 0; n != 1; i++)
            {
                if (n % 2 != 1)
                {
                    n = n / 2;
                    cnt++;
                }
                else {
                    n = (3 * n + 1) / 2;
                    cnt++;
                }
            }
        }
        
    }
    cout << cnt << endl;
    return 0;
}

按照题目的意思应该是进入循环之前先判断n的奇偶性吧。

修改如下,供参考:

#include<iostream>
using namespace std;
int main()
{
    int n = 0, cnt = 0;
    cin >> n;
    if (n <= 0 || n > 1000)
          cout << "wrong" << endl;
    else {
          while(n!=1)
          {
            if (n % 2 == 0)
            {
                n = n / 2;
                cnt++;
            }else {
                n = (3 * n + 1) / 2;
                cnt++;
            }
          }
    }
    cout << cnt << endl;
    return 0;
}

这种一般是临界值或者输入的数较大超时问题

img