Click here to Skip to main content
15,918,108 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am multiplying a double with double then why answer is int

What I have tried:

#include<bits/stdc++.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    while(t--){
        double n=2.00;
        cout<<n*3.00;
    }
}
Posted
Updated 10-Jan-19 21:16pm

No, it's not! :laugh:
It's just that cout defaults to an "unformatted double" which removes trailing zeros after the decimal point.
If you change your code to this:
C++
while(t--){
    double n=0.2;
    cout<<n*3.00<<"\n";
}

It will print "0.6" t times.
You can also use fixed to "force" decimal places:
C++
cout<< fixed <<n*3.00<<"\n";
Which will give you "6.000000"
Or you could combine it with setting the precision to give you two decimal digits:
C++
int main()
{
    cout<<"Hello World";
    int t;
    cin>>t;
    cout.precision(2);
    while(t--){
        double n=2.00;
        cout<< fixed <<n*3.00<<"\n";
    }
    return 0;
}
 
Share this answer
 
Comments
CPallini 11-Jan-19 3:16am    
5.
A little test
C++
#include <iostream>
using namespace std;

int main()
{

  double d = 10;
  int i = 10;

  cout << boolalpha;

  cout << ( typeid(d*2) == typeid(double) ) << "\n";
  cout << ( typeid(i*2) == typeid(double) ) << "\n";

  cout << ((d*2)/3) << "\n";
  cout << ((i*2)/3) << "\n";

}

output:
true
false
6.66667
6
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900