将C十进制转换为无数组的二进制
问题描述:
我想我已经差不多了,但我觉得我正在试图弄清楚这一点。 无需使用字符串或数组即可实现out cout的挑战。我以56作为例子,56应该等于111000,事实并非如此,因为它通过罚款直到7,然后数字等于数字* 2 +数字%2使其等于15并输出全1。 Idk了,这会把我赶到月球和后面。将C十进制转换为无数组的二进制
#include <iostream>
using namespace std;
int main()
{
int number = 0;
int n = 1;
int x = n;
cin>>number;
cout<<n%2;
while(n <= number)
{
if(n%2 == 0)
{
n = n*2;
cout<<0;
}
else
{
n = n*2 + n%2;
cout<<n%2;
}
}
}
答
可以使用二进制运算符&检查单位为1或0
for (int i=512; i>0; i/=2) {
cout << ((number & i) != 0) ;
}
注意,这将导致打印0的。 另外,我假设你只想打印正整数。
备选:
for (int i=512; i>0; i/=2) {
if (number >= i) {
cout << 1;
number -= i;
} else {
count << 0;
}
}
答
您可以使用递归
void decimal_to_binary(int decimal)
{
int remainder = decimal % 2;
if (decimal < 1)
return;
decimal_to_binary(decimal/2);
cout << remainder;
}
时分为二在它之前的功能再次调用自身此功能需要小数点,获得其剩余,则检查小数点小于1(大概为0),并返回执行1和0的打印
+0
OOOO这是非常酷且相当先进的东西,我会坚持下去。以后,谢谢。 – victorsh
答
我最近分配给了我这类问题。此代码示例最多可处理10个二进制数字(根据问题指南)并保持提示输入,直到输入0(标记值)。这当然可以改善,但数学是正确的:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//Declare Variables
int inputValue = 0;
int workingValue = 0;
int conversionSum = 0;
//Begin Loop
do{
//Prompt for input
cout << "Enter a binary integer (0 to quit): ";
cin >> inputValue;
//Reset Variables
workingValue = inputValue;
conversionSum = 0;
//Begin processing input
//10 digits max, so 10 iterations
for (int i=0; i<10; i++) {
//Check for non-binary entry
if ((workingValue % 10) != 1 && (workingValue % 10 != 0)){
cout << "Invalid!\n";
workingValue = 0;
conversionSum = 0;
break;
}
//check to see if 2^i should be added to sum
if (workingValue%2 == 1){
conversionSum += pow(2,i);
workingValue--;
}
//divide by 10 and continue loop
workingValue= workingValue/10;
}
//output results
cout << "converted to decimal is: " << conversionSum << endl;
}while (inputValue != 0);
}
好的解决方案,但不需要每次调用pow。你可以从i = 2^64开始,每次迭代除以2(移一)。 – patros
我不能使用数学函数,没有幂:( – victorsh
我已经更新了解决方案与patros的建议,并添加了一种替代方法。 – DXsmiley