First of all i would just like to thank anyone who replies to this post, i feel very awkward asking for help as i prefer to solve it myself but, being very new to C++, i am having trouble with strings
I am just writing a simple program to convert a real number to binary and managed to get it working in a linear form. However, mostly for practice, partly for general organisation and for further development i decided to break it up into discrete functions. To output the binary at the end of the primary function (binary_conv) i decided to make a string with the binary digits within it. however, the output of the function is nonsensical and seems to be probably a value in the general memory. I am quite sure that return is probably not the right way to output a string but i am not aware of an alternative. I have used several cout s in my quest to solve this problem. I am sure my code is not the most elegant but is seems to get the job doneThanks again! I enclose the code below:
PeterCode:#include <iostream> #include <math.h> using namespace std; int digits(int number); int binary_conv(int digits, int real_number); int main() { for(int x= 0; x<=10; x++) { int real; cout<<"Please enter a real number: "; cin>>real; int c=digits(real); int binary=binary_conv(c,real); cout<<binary <<"\n"; } } int digits(int number) /* calculates the number of digits needed, ie. 101 = 3 digits */ { float b = (float) number; int c = 0; while(b>=1.0) /* simply divides by two until b is less than 1 and counts the number of divisions */ { b=b/2.0; c++; } return c; } int binary_conv(int digits, int real_number) { char *binary = new char[digits+1]; /* I am not at all sure of this part */ float b=(float)real_number; /* Convert the number into a float for processing */ while(digits>0) /* Processes the real number through the repitition of a simple sequence*/ { b=b/(pow(2,digits-1)); /* Dividing the real number by an appropriate bit value (starting at the highest for the number and decreasing) determines the state of the bit*/ if(b>=1) { strcat(binary,"1"); /* If a number higher than one is returned the program outputs a 1 */ cout<<"1"; /* Used to check the byte before the function outputs it */ b=b-1; } else { strcat(binary,"0"); /*If the bit is too big the program outputs a 0 */ cout<<"0"; /* Used to check the byte before the function outputs it */ } b=b*(pow(2,digits-1)); /* Turns the remainder into an appropriate value to continue the loop */ digits=digits-1; } cout<<"\n"<<binary <<"\n"; /* Another check i was using */ return *binary; /* This is almost certainly a major part of the problem */ delete [] binary; }



LinkBack URL
About LinkBacks




but its useful to know this stuff anyways as i have no idea about any of it!