我的代码对一些大数字不起作用

时间:2014-01-23 05:22:05

标签: c++

我有这个代码适用于大多数输入但有一些让我错误。例如“-1000000000000000000 1 1000000000000000000”。

#include <iostream>
#include <cstdio>

using namespace std;
int x,y,m;
int aux=0;
int toPerfect(int a,int b,int per){
    if(a >= per || b >= per){
         aux=0;

    }else if(a<=0 && b<=0){
                 aux = -1;
           }else{
                 while(a < per && b < per){
                      if(a > b){
                           b = b+a;
                       }else{
                             a = a+b;   
                            }
                      aux++;        
                }
               }

     return aux;
}

int main(){
    cin >>x>>y>>m;
    cout << toPerfect(x,y,m) << endl;
    cin.get();

}

2 个答案:

答案 0 :(得分:2)

你在看Integer Overflow。这个问题在这里经常被问到,或许应该有一个有这个名字的专用论坛。

  

...算术运算尝试时发生整数溢出   创建一个太大而无法在其中表示的数值   可用存储空间。例如,将1加到最大值   可以表示的是整数溢出。最多   这些案件的共同结果是最不重要的   要存储的结果的可表示位(结果被称为   套)。

答案 1 :(得分:2)

我在这里提到的一些数据类型的范围。检查出来根据要求更改您的代码。

signed char: -127 to 127
unsigned char: 0 to 255
signed short: -32767 to 32767
unsigned short: 0 to 65535
signed int: -32767 to 32767
unsigned int: 0 to 65535
signed long: -2147483647 to 2147483647
unsigned long: 0 to 4294967295
signed long long: -9223372036854775807 to 9223372036854775807
unsigned long long: 0 to 18446744073709551615
相关问题