简体   繁体   English

C++ 的 Atom 编译器给了我错误的 output 将值转换为二进制

[英]Atom Compiler for C++ gives me wrong output for converting a value to binary

So I have written a code for printing first 20 Binary Numbers like 0 1 10 11 100 101 and so on...所以我写了一个代码来打印前 20 个二进制数,比如 0 1 10 11 100 101 等等......

I Tried running the code in Atom Editor it's not accurate but when I ran the same code in an Online compiler it gave me a correct answer which I expected我尝试在 Atom 编辑器中运行代码,它不准确,但是当我在在线编译器中运行相同的代码时,它给了我一个正确的答案,这符合我的预期

This is the code that I used:这是我使用的代码:

#include<iostream>
#include<math.h>

using namespace std;

 int toBinary(int num){
   int ans = 0;
   int i = 0;
   while(num!=0){
     int bit = num&1;
     ans = ( bit * pow(10,i) ) + ans;

     num = num>>1;
     i++;

   }
   return ans;
 }

int main(){

  for(int i=0;i<20;i++){
    cout<<toBinary(i)<<endl;
  }

  return 0;
}

This is the output i'm getting in ATOM editor:这是我在 ATOM 编辑器中得到的 output:

0 1 10 11 99 100 109 110 1000 1001 1010 1011 1099 1100 1109 1110 9999 10000 10009 10010

And this is the output I'm getting in Online Compiler (this is the output I expect):这是我在在线编译器中得到的 output(这是我期望的 output):

0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001 10010 10011

pow is a floating point function and should not be used for integers. pow是一个浮点数 function,应用于整数。

It is also not required (from efficiency point of view) to recalculate the exponent from scratch every iteration.也不需要(从效率的角度来看)每次迭代都从头开始重新计算指数。 You can just keep a variable and multiply it by 10 in each one.您可以只保留一个变量,然后在每个变量中将其乘以 10。

You can try the code below:您可以尝试以下代码:

#include<iostream>

int toBinary(int num) 
{
    int ans = 0;
    int exp = 1;
    while (num)
    {
        int bit = num & 1;
        ans += bit * exp;
        // for next iteration:
        exp *= 10; 
        num /= 2;
    }
    return ans;
}

int main() 
{
    for (int i = 0; i < 20; i++) 
    {
        std::cout << toBinary(i) << std::endl;
    }
}

Output: Output:

0
1
10
...
10001
10010
10011

Note that the result will overflow pretty fast (2000 is already way to big for representing binary in an int the way you do).请注意,结果将很快溢出(2000 年已经很大,可以按照您的方式用 int 表示二进制)。

A side note: Why is "using namespace std;"旁注: 为什么“使用命名空间标准;” considered bad practice? 被认为是不好的做法? . .

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

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