c - Program only works with small numbers
问题描述
Here's the sample problem:
Lili is a celebrity on a social media platform called GI. She already has 1 million followers in 3 weeks. Bibi also wants to have a lot of followers, then Bibi asked Lili. After Bibi got advice from Lili, her followers doubled everyday. Now Bibi wants to know how many followers Bibi will have after K days from now if she has N follower today.
Constraints: 1 <= N <= 128; 1 <= K <= 30;
Here's my code so far:
#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);
}
The thing is this code only works with smaller numbers. When I try to enter N as 2 and K as 30, the results ends up being negative. Tried with some bigger combinations of N and K and I get 0. I do get the desired results with smaller numbers like 7 and 3, so I thought it was a problem with variable size, but using unsigned long didn't help either. N = 2 and K = 30 still ended up as -2147483648.
How do i meet the constraints given?
解决方案
如果您正在操作的输入,您的data-type
选择很大程度上取决于范围。然而,选定的data-type
有一个限制(很大程度上取决于处理器和其他东西,但这个链接现在应该做)并且超过限制最终会导致溢出。
在您的情况下,范围是1 <= n <= 128
and1 <= k <= 30
并且for-loop
对于最高可能的输入n = 28
和k = 38
评估为
n = 128*(2 pow 0) + 128*(2 pow 1) + 128*(2 pow 2) + 128*(2 pow 3) + .. + 128*(2 pow 29)
上面的结果值n
远远超过了int
可以容纳 vitz 的最大值,2147483647
结果你遇到了integer overflow。
推荐阅读
- node.js - 我如何在 Nodejs 中添加、导入和要求
- xcode - 导航视图宽度
- security - 由“低级”管理员分配安全角色
- ethereum - Solidity:如何在函数修饰符中应用 OR 运算符?
- javascript - 是否可以重复使用 wordpress woocommerce 产品库
- sql - “SQL 错误或缺少数据库(没有这样的列”但存在列的表)
- python - IDLE 控制台中 Flask 应用程序的导入错误
- typescript - 扩大 TypeScript 中的 const 文字类型
- python - 删除出现在整个数据框中的特定值
- neo4j - 是否可以在 Cypher 中“重复”不止一跳的模式?