Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 我的itoa没有';我不能和大数字打交道_C - Fatal编程技术网

C 我的itoa没有';我不能和大数字打交道

C 我的itoa没有';我不能和大数字打交道,c,C,我被指派执行itoa,我的代码与-2147483648不兼容。我怎样才能让它工作 char *itoa(int nbr) { static char rep[] = "0123456789"; static char buff[65]; char *ptr; int neg; ptr = &buff[64]; *ptr = '\0'; neg = nbr; // fails here,

我被指派执行
itoa
,我的代码与
-2147483648
不兼容。我怎样才能让它工作

char    *itoa(int nbr)
{
    static char rep[] = "0123456789";
    static char buff[65];
    char        *ptr;
    int         neg;

    ptr = &buff[64];
    *ptr = '\0';
    neg = nbr;
    // fails here, turning -2147483648 to int
    //2147483648 is bigger than int.
    if (nbr < 0)
        nbr *= -1;
    if (nbr == 0)
        *--ptr = rep[nbr % 10];
    while (nbr != 0)
    {
        *--ptr = rep[nbr % 10];
        nbr /= 10;
    }
    if (neg < 0)
        *--ptr = '-';
    return (ptr);
}
char*itoa(内部编号)
{
静态字符代表[]=“0123456789”;
静态字符buff[65];
char*ptr;
int neg;
ptr=&buff[64];
*ptr='\0';
neg=丁腈橡胶;
//此处失败,将-2147483648转为int
//2147483648大于int。
如果(nbr<0)
nbr*=-1;
如果(nbr==0)
*--ptr=代表[nbr%10];
而(nbr!=0)
{
*--ptr=代表[nbr%10];
nbr/=10;
}
如果(负<0)
*--ptr='-';
返回(ptr);
}

正如您在代码中的注释所说,这个数字太大,int无法处理。尝试使用long,它的范围要大得多,应该可以存储2147483648。

您正在尝试使用以下代码将-2147483648转换为2147483648

if (nbr < 0)
  nbr *= -1;

了解限制……我不能使用
long
,我的函数原型要求
nbr
int
。对不起,这有助于解决问题吗?你能详细说明一下吗?当输入整数为-2147483648时,运算算法不工作,因为运算算法试图将其转换为2147483648
int
未在OP系统中处理此类值。C99标准规定
long-long
应至少能够处理9223372036854775807以下的值。在算法中使用
long
解决OP所指的问题。
long long my_positive = nbr;
if (my_positive < 0)
      my_positive*= -1;