0
Separating a number into integral and fractional part
How to separate for example 12.345 into its integral part and fractional part? like integral part is 12 and fractional part is 0.345 in C++?
7 Antworten
+ 4
Daniel
I wish you linked your attempts on this problem in this post.
https://www.sololearn.com/post/75089/?ref=app
Anyways,
What part feels you hard make in this?
It's really simple.
Just go with your own given example.
double n = 12.345;
12.345
/ \
/ \
12. 0.345
As you can see for integer part you have to skip part after decimal point.
For this you can typecast your `double` or `float` to `int`
Typecast it and store in a variable.
int integer_part=(int)n;
Next the fractional part can be obtained by dividing integer part from fractional number.
12.345 - 12 =0.345;
For this
double fractional_part = n - integer_part;
Keep practicing.
+ 2
You can try function `modf` from cmath header:
Reference (example included)
http://www.cplusplus.com/reference/cmath/modf/
+ 1
Daniel
Well done ~
The problem is that you should take input for variable before you do any calculations using it. Otherwise it will contain some random(garbage) value.
https://www.sololearn.com/Discuss/1654860/?ref=app
So all you need to do is write line 10 and 11 after declaration of `n`.
And don't forget to print values of `integer_part` and `fractional_part`
Not using them ,you'll get warning by SL compiler.
0
🇮🇳Omkar🕉 //Busy , Exams. how about if i want the user to input any number not just static number? is it the same?
0
Ipang i try to implement that
0
Daniel ,
Yes . it's same even if you try with user inputs.
0
🇮🇳Omkar🕉 //Busy , Exams.
https://code.sololearn.com/c9OCKwu3jPzi/?ref=app why i cant use the cin for n?