+ 3
Problem with decimal values
Help,I know I am doing something wrong here and the answer is pretty obvious yet I can't figure it out. I think the output should have been a decimal value(upto some decimal point if cpp cant handle irrational values).But the output is integer value much like modulus(%) //code here https://code.sololearn.com/c2Ld7UjF2FfH/?ref=app
7 Réponses
+ 4
(i) Only one of them need to be float. So instead of 22 write 22.0 or float(22).
(ii) float pi = int(22) / int(7); => float pi = 3; => cout << pi; // would be 3.
+ 4
(int) / (int) will result in int. Write (float)22 / 7 then you will see 3.14!
+ 2
thanks soheil,
that answered my query regarding the output of a integer in the cout statement.
Modifying that line will now result in a decimal value
cout<<22.0/7;
output-3.14
//and not cout<<22/7; resulting in a integer (3)
//thanks for reminding me that concept
but what about this statement
float pi;
pi=22/7;
(i)do I still have to convert 22 to 22.0 and 7 in the similar way?
(ii)isn't pi already declared a float type so by my guess(which could be wrong here) it should print out a decimal containing value?
+ 1
ahh ok!
so for float, either values should contain a decimal or float(any integer here) both are valid.
That was really helpful thanks and have a great day ahead!
+ 1
0
(ii) https://www.oreilly.com/library/view/practical-c-programming/0596004192/ch04.html#:~:text=C%2B%2B%20uses%20the%20decimal%20point,8.88%20are%20floating%2Dpoint%20numbers.
0
Ice_Bear You're welcome :))