Hello and welcome to our community! Is this your first visit?
AdSlot7
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Help with a homework assignment

1. ## Help with a homework assignment

Hello, i am a noob in C++ as my nick says, and my homework for tomorrow is to make a c++ code that converts decimal into other bases (from 2 to 16). This is what i've made so far:

Code:
```#include <iostream>
#include <string>
using namespace std;
void toBase(int n, int base)
{
string alpha="0123456789ABCDEF";
if (n > 0)
{
toBase(n/base,base);
cout << alpha[n%base];
}
}
main()
{
float num, b;
cout << "";
cin >> num;
cout <<"";
cin >> b;
toBase(num,b);
cout << "." << b << endl;
}```
And these are the results:

10.5 = 1010.1 = 1010.2
2

3.827 = 10.2110222122 = 10.3
3

82.7593 = 101.6744681322 = 101.9
9

7218.8192 = 5472.90139A8535 = 5472.11
11

8273.8 =26B8.C = 26B8.15
15

23517.75 =5BDD.C = 5BDD.16
16

92.33271 = 1011100.0101010100 = 1011100.2
2

4095.839 = 7777.6554426416 = 7777.8
8

29672.9311 = 13033220.3232113021 =13033220.4
4

9999.987 = 270F.FCAC083126 = 270F.16
16

The first numbers are the input (the decimal number and the base), the second number are what i should get in order for it to be correct, the third number is what i get. I messed up at the decimals, i tried with iomanip and setprecision to add 10 decimals (the assignment says that if a number has more than 10 decimal places, it should show only the first ten), but it doesn't work, they're always wrong (and always numbers). Any help will be appreciated.

2. AdSlot6
3. It looks like it is the fraction part that is always wrong - possibly because floating point numbers are never exact when it comes to number bases other than 2. Have you considered multiplying by 1e10 first before converting and then shifting the decimal point back to the right place afterwards?

4. Originally Posted by felgall
It looks like it is the fraction part that is always wrong - possibly because floating point numbers are never exact when it comes to number bases other than 2. Have you considered multiplying by 1e10 first before converting and then shifting the decimal point back to the right place afterwards?
When i tried that i got

p_60133.cpp: In function ‘int main()’:
p_60133.cpp:17:16: warning: overflow in implicit constant conversion [-Woverflow]

and the same results.

5. My mistake is that i'm entering a float, which will be cast in to an integer when calling the toBase function. Hence, the fractional part of the number is gone at this moment. Then, in the very last line of main, i output "." << b, b being the base.

However, i'm still stumped and don't know how to proceed, should i change the int in toBase to float, and then use fmod for this part?

toBase(n/base,base);
cout << alpha[n%base];

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•
AdSlot4
AdSlot5