我可以将4294967295存储在unsigned int中吗? Int在我的机器上是4个字节 [英] Cant i store 4294967295 in unsigned int ? Int is 4 bytes on my machine

查看:339
本文介绍了我可以将4294967295存储在unsigned int中吗? Int在我的机器上是4个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我得到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 store 4294967295 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 in unsigned int, but the problem is in your printing, you are doing printf("%d", 4294967295) which means print 4294967295 as a signed int, but the number 4294967295 cannot be stored in signed 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屋!

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