+ 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.
17 Respuestas
+ 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.
+ 8
Use double
+ 6
Armina your welcome
+ 5
Sololearn probably has limitation on number of decimal points.
+ 5
Thanks
+ 4
Float has only 4 digit precision and the 5th digit is rounded off here on sololearn playground.
+ 4
Why don't you try it on a system or a laptop
+ 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
+ 1
I used cxxdriod
Is it different on laptop?
+ 1
Yes
+ 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?
+ 1
Thank you so much Kit Delano Cat, I just learnt something new today.
0
I tried 10.0/3 and it showed with only 5 digits not seven
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)
0
How can I have more digits ?
0
I used it but as I said it only showed 5 digits
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