C++ 十进制到二进制,用C++;

C++ 十进制到二进制,用C++;,c++,C++,这就是我所拥有的: string decimal_to_binary(int n){ string result = ""; while(n > 0){ result = string(1, (char) (n%2 + 48)) + result; n = n/2; } return result; } 这是可行的,但是如果我输入一个负数就不行了,有什么帮助吗?只要 #include <bitset> #包括 然后使用位集和到字符串将int转换为字符串 s

这就是我所拥有的:

string decimal_to_binary(int n){
string result = "";
while(n > 0){
    result = string(1, (char) (n%2 + 48)) + result;
    n = n/2;
}
return result; }
这是可行的,但是如果我输入一个负数就不行了,有什么帮助吗?

只要

#include <bitset>
#包括
然后使用位集到字符串将int转换为字符串

std::cout << std::bitset<sizeof(n)*8>(n).to_string();
std::cout
这行得通,但如果我输入一个负数就不行了,有什么帮助吗

检查数字是否为负数。如果是,请使用
-n
再次调用该函数并返回连接的结果

您还需要添加一个子句来检查0,除非您希望在输入为0时返回空字符串

std::string decimal_to_binary(int n){
   if ( n < 0 )
   {
      return std::string("-") + decimal_to_binary(-n);
   }

   if ( n == 0 )
   {
      return std::string("0");
   }

   std::string result = "";
   while(n > 0){
      result = std::string(1, (char) (n%2 + 48)) + result;
      n = n/2;
   }
   return result;
} 
std::字符串十进制到二进制(int n){
if(n<0)
{
返回std::string(“-”)+十进制到二进制(-n);
}
如果(n==0)
{
返回标准::字符串(“0”);
}
std::string result=“”;
而(n>0){
结果=标准::字符串(1,(字符)(n%2+48))+结果;
n=n/2;
}
返回结果;
} 

我建议为负数调用一个单独的函数。例如,假设,-1和255都返回11111。从正数到负数的转换将是最容易的,而不是完全改变逻辑来处理两者

从正二进制到负二进制只需运行XOR并加1

您可以像这样修改代码以获得快速修复

string decimal_to_binary(int n){
    if (n<0){ // check if negative and alter the number
        n = 256 + n;
    }
    string result = "";
    while(n > 0){
        result = string(1, (char) (n%2 + 48)) + result;
        n = n/2;
    }
    return result;
}
字符串十进制到二进制(int n){
if(n0){
结果=字符串(1,(字符)(n%2+48))+结果;
n=n/2;
}
返回结果;
}

检查
n的负值
并采取适当的措施。您希望函数对负值做什么?请澄清您的问题。。你把负数放在哪里?如果
n
为负,则
while(n>0)
无法输入,因此返回空字符串。这是你的本意吗?最好发布一个能产生一些输出的,并解释输出与您想要的不同之处。@M.M-是的,n是我的值。我刚刚意识到我的n>0。我是否需要if语句来区分负数和正数?这是一个选项,但您仍然没有显示负数
n
的行为,您可以用32位代码执行同样的操作吗?