我可以将4294967295存储在unsigned int中吗? Int在我的机器上是4个字节 [英] Cant i store 4294967295 in unsigned int ? Int is 4 bytes on my machine
问题描述
为什么我得到0?编译器警告:
格式'%d'需要类型为'int'的参数,但参数3的类型为'long unsigned int'<这是代码:
> #include< stdio.h>
//函数declerations ...
int power(int base,int on);
int main(void){
printf(%d,power(2,sizeof(int)* 8)-1);
返回0;
}
int power(int base,int on){
int pf = 1;
for(int i = 0; i< on; i ++){
pf * = base;
}
返回pf;
}
如果int是我系统上的4个字节,我猜我应该能够在无符号 int中存储4294967295。
解决方案我很久以后回来了时间(很明显)到这个问题,我不知道为什么每个人都认为OP意味着存储
4294967296
当他想存储4294967295
如问题所述,也许OP后来改变了问题,没有人费心去重新回答。现在,回到问题。
您可以在
unsigned int $中存储
4294967295
c $ c>,但问题在于你的打印,你正在做printf(%d,4294967295)
这意味着打印4294967295
作为signed int
,但数字4294967295
无法存储在中signed int
,因此,缩小转换。
您需要打印
unsigned int
你已经%u
而不是%d
。#include< stdio.h>
int power(int base,int pow);
int main(){
printf(unsigned int的大小:%d \ n,sizeof(unsigned int));
unsigned int the_number = power(2,sizeof(int)* 8)-1;
printf(Wrongly printed:%d \ n,the_number);
printf(正确打印:%u \ n,the_number);
返回0;
}
int power(int base,int on){
int pf = 1;
for(int i = 0; i< on; i ++){
pf * = base;
}
返回pf;
}
Why am i getting 0 ?? And compiler warning:
format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long unsigned int’
Here is the code :
#include <stdio.h> //function declerations... int power(int base, int on); int main(void) { printf("%d",power(2, sizeof(int)*8)-1); return 0; } int power(int base, int on) { int pf = 1; for (int i = 0; i < on; i++) { pf *= base; } return pf; }
If int is 4 bytes on my system,i guess i should be able to store 4294967295 in unsigned int.
解决方案I am back after long time (obviously) to this question, and I am not sure why everyone thinks OP meant to store
4294967296
when he wanted to store4294967295
as asked in the question, maybe OP changed the question later, and no one bothered to re-answer. Now, back to question.You can store
4294967295
inunsigned int
, but the problem is in your printing, you are doingprintf("%d", 4294967295)
which means print4294967295
as asigned int
, but the number4294967295
cannot be stored insigned int
, so, narrowing conversion happens.You need to print the
unsigned int
that you've got with%u
rather than%d
.#include <stdio.h> int power(int base, int pow); int main(){ printf("Size of unsigned int: %d\n", sizeof(unsigned int)); unsigned int the_number = power(2, sizeof(int)*8)-1; printf("Wrongly printed: %d\n", the_number); printf("Correctly printed: %u\n", the_number); return 0; } int power(int base, int on) { int pf = 1; for (int i = 0; i < on; i++) { pf *= base; } return pf; }
这篇关于我可以将4294967295存储在unsigned int中吗? Int在我的机器上是4个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!