- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是示例问题:
Lili 是 GI 社交媒体平台上的名人。三周内她已经拥有 100 万粉丝。比比也想有很多追随者,然后比比问莉莉。比比得到莉莉的建议后,她的粉丝每天翻倍。现在Bibi想知道如果Bibi今天有N个关注者,K天后Bibi将会有多少个关注者。
限制:1 <= N <= 128;1 <= K <= 30;
这是我到目前为止的代码:
#include<stdio.h>
int main(){
int n,k,temp;
scanf("%d %d",&n,&k);
for(temp = 1; temp <= k; temp++){
n = n * 2;
}
printf("%d\n",n);
return(0);
}
问题是此代码仅适用于较小的数字。当我尝试输入 N 作为 2、K 输入 30 时,结果最终为负数。尝试使用一些更大的 N 和 K 组合,我得到 0。我确实用较小的数字(如 7 和 3)得到了所需的结果,所以我认为这是可变大小的问题,但使用 unsigned long 也没有帮助。 N = 2 且 K = 30 最终仍为 -2147483648。
我如何满足给定的限制?
最佳答案
这是由于integer overflow :
In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of digits – either larger than the maximum or lower than the minimum representable value.
换句话说,您使用的数据类型无法存储大于特定值的数字。选择另一种类型来存储更大的数字(例如,使用 unsigned long long
而不是 int
)。还存在提供可以存储任意大数字的类型的库,通常以处理速度为代价。
您应该使用某种无符号整数的另一个原因是答案永远不会是负数。这会释放表示数字符号的位,并将可存储的值的正范围加倍。
关于c - 程序仅适用于少量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52658155/
我是一名优秀的程序员,十分优秀!