Float and double in c++ | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
+ 4

# Float and double in c++

What's wrong with this program? I know that float accommodates 7 digits and double 15 to 16 digits but why this program show result with 5 digits as the default. #include <iostream> using namespace std; int main() { float a; a=10/3; cout<<a; return 0; } The result is 3 with no digits.

5th Nov 2019, 4:37 PM
Armina
17 Réponses
+ 11
Because 10 and 3 are integers and their division results in 3. Change it to a= (float) 10/3; You have to type cast it to float.
5th Nov 2019, 4:40 PM
Avinesh
+ 8
Use double
5th Nov 2019, 4:48 PM
Avinesh
+ 6
5th Nov 2019, 4:54 PM
Avinesh
+ 5
Sololearn probably has limitation on number of decimal points.
5th Nov 2019, 4:51 PM
Avinesh
+ 5
Thanks
5th Nov 2019, 4:53 PM
Armina
+ 4
Float has only 4 digit precision and the 5th digit is rounded off here on sololearn playground.
5th Nov 2019, 4:44 PM
Avinesh
+ 4
Why don't you try it on a system or a laptop
5th Nov 2019, 4:50 PM
Avinesh
+ 4
The reason is the order of operation of the program 1. divide the two integers (10/3=3) 2. Cast the result to float (=3.0) 3. Store the result in a As said before, there are to solutions One is to cast one of the number or both to float a=(float) 10 /3; The operations are 1. Cast 10 to float (10.0) 2. Cast 3 to float, needed to make the division (3.0) 3. Divide 10.0/3.0 (=3.33333...) 4. Store the result to a Or better put directly float numbers a=10.0/3.0; Which does: 1. Divide 10.0/3.0 (=3.3333) 2. Store the result into a
5th Nov 2019, 10:46 PM
David Frydman
+ 1
I used cxxdriod Is it different on laptop?
5th Nov 2019, 4:52 PM
Armina
+ 1
Yes
5th Nov 2019, 4:52 PM
Avinesh
+ 1
Thanks Kit Delano Cat When we use fixed or setprecision, does mentioning float or double matter, I mean what if we don't write float or double?
7th Nov 2019, 1:54 PM
Armina
+ 1
Thank you so much Kit Delano Cat, I just learnt something new today.
7th Nov 2019, 2:36 PM
Hilary
0
I tried 10.0/3 and it showed with only 5 digits not seven
5th Nov 2019, 4:43 PM
Armina
0
I read that float has 7 digits l even tried this one #include <iostream> using namespace std; int main() { double a; a=10.0/3; cout<<a; return 0; } the result was 3.33333 (only 5 digits)
5th Nov 2019, 4:45 PM
Armina
0
How can I have more digits ?
5th Nov 2019, 4:47 PM
Armina
0
I used it but as I said it only showed 5 digits
5th Nov 2019, 4:49 PM
Armina
0
Because here 10 and 3 both are integers so in c++ output of operation of all integers will be a integer so get output in floating point number use 3.0 or 10.0 or both
7th Nov 2019, 2:36 PM
Arindam Mondal
Aujourd'hui en vedette