有关int范围的例题(算法竞赛入门经典)

对于任意大于1的自然数n,若n为奇数,则将n变为3n1,否则变为n的一半。
经过若干次这样的变换,一定会使n变为1。 例如,3→10→5→16→8→4→2→1
输入n,输出变换的次数。 n≤109
样例输入:
3
例输出:
7

 1 #include<iostream>
 2 #include<iomanip>
 3 #include<cmath>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int n;
 9     cin >> n;
10     int count = 0;
11     while (n != 1)
12     {
13         if (n % 2 == 0)
14         {
15             n = n / 2;
16             
17         }
18         else
19         {
20             n = 3 * n + 1;
21             
22         }
23         count++;
24     }
25     cout << count << endl;
26     system("pause");
27     return 0;
28 }

对于样例可以正确输出结果,但是当输入987654321时,却不能输出正确结果,为什么呢?int的大小应该是-2147483648-2147483647,已经超出int的范围,将n的类型定义为long long,就可以直接输出180.

 1 #include<iostream>
 2 #include<iomanip>
 3 #include<cmath>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     long long  n;
 9     cin >> n;
10     int count = 0;
11     while (n != 1)
12     {
13         if (n % 2 == 0)
14         {
15             n = n / 2;
16             
17         }
18         else
19         {
20             n = 3 * n + 1;
21             
22         }
23         count++;
24     }
25     cout << count << endl;
26     system("pause");
27     return 0;
28 }
原文地址:https://www.cnblogs.com/wujufengyun/p/6889610.html