简体   繁体   English

c++ 奇怪的错误与十进制到二进制转换器

[英]c++ weird error with decimal to binary converter

I'm a complete newbie to C++ programming.我是 C++ 编程的新手。 I've been given the task to code decimal to hexadecimal,octal,binary conversion.I have encountered errors in the "binario" function, when I enter a decimal number greater than 1000 the function gives me a result as a nonsense random numbers.我被赋予了将十进制编码为十六进制、八进制、二进制转换的任务。我在“binario”function 中遇到错误,当我输入一个大于 1000 的十进制数时,function 给了我一个无意义的随机数结果。

int binario(int n){
    int r,val=0, i=1;
    while (n>0) {
      val=val+(n%2*i);
      n=n/2;
      i=i*10;
   }
   return val;
}


In C++, the maximum size for int is 4 bytes which means from -2,147,483,648 to 2,147,483,647.在 C++ 中,int 的最大大小为 4 个字节,即从 -2,147,483,648 到 2,147,483,647。 Binary of 1024 is 10000000000 and it's more than int range. 1024 的二进制是 10000000000,它超过了 int 范围。 This is why you see the error.这就是您看到错误的原因。 You can use your function for numbers less than 1024. I suggest you using string for your function(you have to include string header):您可以将 function 用于小于 1024 的数字。我建议您使用字符串作为函数(您必须包含字符串标题):

string binario(int n){
    string bin = "";
    while (n>0) {
      bin += to_string(n%2);
      n=n/2;
   }
   //reverse string
   for (int i = 0; i < bin.size() / 2; i++) {
    swap(bin[i], bin[bin.size() - i - 1]); 
   } 

   return bin;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM