Hello everybody. I've written a program which can convert decimal numbers to binary numbers. But I was wondering whether it's possible to modify this code to accept decimal values as well, like 100.14, etc.
#include<iostream>
usingnamespace std;
int main ()
{
int n,r,i=0,flag=0;
int ch[16];
cout<<"Enter the value of n as a decimal number : ";
cin>>n;
while (n!=0)
{
r=n%2;
n=n/2;
ch[i]=r;
i++;
flag++;
}
cout<<"The number is : ";
for (i=flag-1;i>=0;i--)
cout<<ch[i]<<" ";
}
Is this code any good or are there any errors or loopholes ?
possible to modify this code to accept decimal values as well, like 100.14
Well if you know something about templates and typeinfo inquiry then that's possible
You don't need to increment i at line 14 since you'll reset the value at line 18.
Stylistically, it would be better to put i completely within the for loop at line 18. Also, I urge you to always use braces, even when they are redundant. Do this because otherwise, at 2AM you'll decide that you need 2 statements inside the for loop (or whatever doesn't have the braces) and you'll add it in. In other words, you'll go from this:
1 2
for (int i=0; i<count; ++i)
do_something;
to this:
1 2 3
for (int i=0; i<count; ++i)
do_something;
and_do_something_else
But without the braces, and_do_something_else is actually outside of the loop. It will take you 4 hours to find this bug.... :)