简体   繁体   English

意外的结果将十进制数转换为二进制

[英]Unexpected results converting decimal number to binary

# include <iostream>
# include <cmath>
using namespace std;
int main()
{

    int p;
    int n;
    int q;
    cin>>n;
    int r;
    r=0;
    for (int i=0,n; n>1; i=i+1,n=n/2)
    {

    p=n%2;
    q= p*(pow(10,i));
    r=r + q;
}

cout<<r;
system("pause");
return 0;
}

I am not supposed to use arrays. 我不应该使用数组。 It compiles fine but when executed and a number is entered, it doesn't produce the desired results. 它可以很好地编译,但是当执行并输入数字时,不会产生期望的结果。 For instance, when 22 is entered, it gives -2147483648 whereas the desired output would be 10110. 例如,当输入22时,它将给出-2147483648,而所需的输出将是10110。

your way is limited and not effient in converting to binary 您的方式是有限的,并且转换为二进制文件效率不高

you should use string it's more helpful and the range is big enough for any number 您应该使用字符串,它更有用,并且范围足够大,可以容纳任何数字

this is my code for decimal-to-binary 这是我的十进制到二进制代码

#include<iostream>
#include<string>
#include<stack>

using namespace std;

int main()
{
   long long n;
   string s,bin;
   stack<string> res;

   cin>>n;
   while(n>0)
   {
     if(n%2==0)
         s='0';
     else
         s='1';
     res.push(s);
     n=n/2;
   }
   while(!res.empty())
   {
     bin=bin+res.top();
     res.pop();
   }
   cout<<bin<<endl;

return 0;
}

I hope it will help you. 希望对您有帮助。

int i=0,n;

should be 应该

int i=0;

I don't know what you thought you were doing there, but what you are actually doing is declaring another variable n . 我不知道您认为您在那儿做什么,但实际上是在声明另一个变量n Because the second n variable doesn't have a value the rest of the code doesn't work. 由于第二个n变量没有值,因此其余代码无效。

That's not the only problem with your code, but I'm sure you can figure out the rest. 这不是代码的唯一问题,但是我相信您可以弄清楚其余的问题。

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

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