Separating a number into integral and fractional part | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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++?

31st Oct 2019, 1:31 PM
Daniel
Daniel - avatar
7 Answers
+ 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.
31st Oct 2019, 1:53 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 2
You can try function `modf` from cmath header: Reference (example included) http://www.cplusplus.com/reference/cmath/modf/
31st Oct 2019, 2:12 PM
Ipang
+ 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.
31st Oct 2019, 3:07 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
0
🇮🇳Omkar🕉 //Busy , Exams. how about if i want the user to input any number not just static number? is it the same?
31st Oct 2019, 2:27 PM
Daniel
Daniel - avatar
0
Ipang i try to implement that
31st Oct 2019, 2:27 PM
Daniel
Daniel - avatar
0
Daniel , Yes . it's same even if you try with user inputs.
31st Oct 2019, 2:30 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
31st Oct 2019, 2:46 PM
Daniel
Daniel - avatar