It's been a long time since I have written code and need a bit of help.
If you have two number x and y, and you want x to be the whole number and y to be the decimal, x.y, how would you code that in C?
Thanks in advance.
It's been a long time since I have written code and need a bit of help.
If you have two number x and y, and you want x to be the whole number and y to be the decimal, x.y, how would you code that in C?
Thanks in advance.
In general, you should look at floor().
In the case that your number could be negative, you're going to have to decide what you mean by the whole number: is -3.8 a whole number of -3 and a decimal of -0.8, or a whole number of -4 and a decimal of 0.2? (One of those is consistent with the positive case, and it probably isn't the one you were planning on.)
My issue is this:
Code:int convert ( int x, int y) { int result; // result = x.y; <-- this is what I need to compute return result; }
int can only hold an integral value, meaning no decimal. When you say you want x.y does that mean that if x = 3 and y = 25, that the result needs to be 3.25? Since y is an int, it can't hold 0.25 itself.
Well if x is a whole number and y is a decimal already, then x.y just means x+y. (I.e. if x is 3 and y .25, then you get 3.25 by doing x+y.)
Code:#include <stdio.h> #include <math.h> double convert( int x, int y ) { double d = y; while( d > 1.0 ) d /= 10.0; return x + d; } double convert2( int x, int y ) { return x + y / pow( 10, floor( log10( y ) + 1 ) ); } double convert3( int x, int y ) { char s[ 100 ]; sprintf( s, "%d.%d", x, y ); double d = 0.0; sscanf( s, "%lf", &d ); return d; } int main() { printf( "%f\n", convert( 1, 23 ) ); printf( "%f\n", convert2( 1, 23 ) ); printf( "%f\n", convert3( 1, 23 ) ); }
The greatest deception men suffer is from their own opinions. - Leonardo da Vinci
Thank you, that was very helpful.