# Thread: simple but not working

1. ## the math way

Alright, thanks for the code examples above.
I will be studying them and will use them once I know and test them better.

Below is the hardway in that it demonstrates the math and could be extended to other bases.

Dave++

Code:
```#include <iostream>
#include <stdio.h>
#include <string>
#include <cmath>
#include <cstdlib>

std::string DecToBin(float num)
{
std::string str = "";
int i, expmax;
double top;
const double lg2 = log(2.0);

if(num == 0) return("0");

expmax = floor(log(num)/lg2);
//  std::cout <<"expmax " << expmax << std::endl;

for(i=expmax; i>=0; i--){
top = num - pow(2.0,i);    // subtract the binary basis
//    std::cout << num << " " << top << std::endl;
if (top < 0){
str = str + "0";
}
else {
str = str + "1";
num = top;
}
}
return(str);
}

int main()
{
int num;
printf("Enter a whole number: ");
scanf("&#37;i", &num);
std::cout << DecToBin(num) << std::endl;
//  std::cout << log(2.0) << std::endl;
}```
____________
If there are no spoons, then where did all the ice cream come from? ("7")

2. just a thought Dave++, here is another way to work it. Not as good as Daved but it does work.
Code:
```#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>

using namespace std;

int main()
{
unsigned long long Dec;
std::stringstream ss;
cout << "Number:";
while ( cin >> Dec )
{
while ( Dec > 0 )
{
ss << (Dec&#37;2);
Dec /= 2;
}
std::string binary = ss.str();
reverse(binary.begin(), binary.end());
cout << "Binary: " << binary << endl;
cout << "New Number: ";
}
}```

3. To Dave++:

<stdio.h> is a C header file. Usually one uses <cstdio>, which puts the functions in <stdio.h> into the namespace std. I see you've included <cmath> instead of <math.h>, but you're using just plain pow() and log() etc. Use either <math.h> and pow() or <cmath> and std::pow.

Also,
Code:
`str = str + "0";`
is the same as
Code:
`str += "0";`
which means, of course, that you can use either. But the latter requires less typing and is less error-prone.

4. DWKS, Raigne,
Thanks for the updates. I'll be using them.

Dave

5. a = a + b and a += b may be semantically equivalent, but they might very well differ in efficiency. Typically, += is considerably more efficient.

6. For appending a single character, an alternative would be:
Code:
`str.push_back('0');`

7. Originally Posted by MacGyver
If you're returning a local string object, that could be why you're seg faulting. I don't think you should return local objects. Someone correct me if I'm wrong....
You shouldn't return REFERENCES to local objects. Returning objects themselves is fine.

8. You shouldn't return pointers to local objects, either. Returning objects by value is okay (assuming that the object has a proper copy constructor!) because the calling function gets a copy of the object.

Popular pages Recent additions