如何在C中停止溢出的数字? [英] How do I stop overflowing numbers in C?

查看:79
本文介绍了如何在C中停止溢出的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了很多这个问题。现在我感到很无聊。这是链接:

模块化计算器 - CodeAbbey [ ^ ]



示例:

i have tried this problem a lot .And I'm getting bored now.HERE is the link:
Modular Calculator - CodeAbbey[^]

Example:

510
* 5
* 9
+ 9
* 9932
* 1925
* 4
+ 918
* 7
* 9307
* 9
+ 96
* 1063
* 4
* 1380
* 100
+ 119
+ 8377
* 718
* 87
* 57
* 7548
* 52
+ 7227
+ 7
+ 1
+ 6204
+ 598
+ 48
+ 740
+ 4698
+ 4
* 81
+ 718
* 90
* 4
* 2065
+ 8741
* 244
+ 93
* 9
+ 8875
* 16
* 76
* 1
* 112
+ 1
+ 9
+ 4450
+ 8859
% 9602





我尝试了什么:





What I have tried:

 #include<stdio.h>
 #include<conio.h>
int main()
{
    int str[1];
    int i , j ,num1;
    char ch;
    scanf("%d",&str[0]);
    while (1)
    {
        ch=getche();
        scanf(" %d",&num1);
        if(ch=='+')
        {
            str[0]=str[0]+num1;
             printf("%d ",str[0]);
        }
        if(ch =='*')
        {
            str[0]=str[0]*num1;
            printf("%d ",str[0]);
        }
        if(ch =='%')
        {
            str[0]=str[0]%num1;
                break;
        }

    }

    return 0;
}

推荐答案

许多可能性:

1)如果你能知道最后一次操作提前,您可以通过在每次操作后连续应用模数来限制值的大小。使用类型 long 就足够了。



2)使用类型 long long 将推出溢出限制,但可能不够大,具体取决于数据。



3)使用 bigint库或无限整数将确保您永远不会溢出。



警告:取决于编译器版本, int 可以小到16位,这个太小,大小 int long long long 可能会有所不同。
Many possibilities:
1) If you can know the last operation in advance, you can limit the size of values by continuously applying the modulo after each operation. Using type long should be enough.

2) Using type long long will push the overflowing limit but may not be large enough depending on data.

3) resorting to a bigint library or "infinite integers" will ensure that you will never have overflow.

Warning: depending on compiler version, size of int can be as small as 16 bits, which is too small, sizes of int, long and long long may vary.


尝试前20或用你的袖珍计算器计算你看到中间结果进入10 ** 20的范围。这对于32位int甚至对于64位int来说太多了。



但是如果你查看给定链接上的任务描述你会看到他们要求模数操作。请注意,您可以使用最后一行中给出的模数执行所有这些操作。现在,在读完所有线之前,你怎么知道模数?嗯,这是你要解决的任务。如果你想一会儿就不那么难了。
Try to the first 20 or calculation with your pocket calculator and you see that the intermediate result gets into the range of 10**20. That is too much for a 32-bit int and even for a 64-bit int.

But if you look at the task description on the given link you see that they ask for modulo operation. Note that you can do all those operations in the modulus given in the last line. Now, how do you know the modulus before you have read all the lines? Well, this is the task for you to solve. It is not that difficult, if you think about it for a minute.


这篇关于如何在C中停止溢出的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆