0

So I have written a code for printing first 20 Binary Numbers like 0 1 10 11 100 101 and so on...

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

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:

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):

0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001 10010 10011
wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • You should explain exactly what you get in your environment (and how it differs from what you expect). Anyway - you shouldn't use `pow` for integers. – wohlstad Jan 27 '23 at 10:31
  • This is the output i'm getting in ATOM editor - 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 - 0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001 10010 10011 @wohlstad – Sarvang Lokhande Jan 27 '23 at 10:36
  • 1
    Don't use pow(10,i) it is a floating point function and thus per definition imprecise. Just multiply an integer by 10 in each iteration of your loop; – Pepijn Kramer Jan 27 '23 at 10:40

1 Answers1

0

pow is a floating point function and should not be used for integers.

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.

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:

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).

A side note: Why is "using namespace std;" considered bad practice?.

wohlstad
  • 12,661
  • 10
  • 26
  • 39