In: Computer Science
Below is the C ++ code for a given assignment. An acre equal 43,560 sq ft. Im supposed to find the total number of acres within a tract of land that is 391,876 sq ft. the program compiles and runs just fine but I'm wondering if it would be better to use the int data type instead? I used double for more accuracy. The instructor didn't say we had to use any certain data type so I'm asking purely for practicality and for real world scenarios which would be better.
// this program calculates the number of acres in a tract of
land
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double acre = 43560,
land =
391876,
total;
//Calculate the total number of acres
total = land / acre;
cout<<"the total number of acres is " <<
total << endl;
return 0;
What you did is exactly right !!!!!!!!!!!!
In practical, we should use double value only.
WHEN SHOULD WE USE INT??
We use int datatype only when we don't get any fractional part in the answer.
Example: Multiplication of two integers will always give an int value only. We never get a fraction.
2*3=6
4*5=20
10*0=0
and so on
ALL are int values, so we can use int for integer multiplication.
WHEN SHOULD WE USE DOUBLE??
we will use double datatype if we know that any fraction may come up in the solution.
Example: DIVISION can always give you a fraction.
3/2=1.5
4/2=2 (we can also take 2.0, a double value)
5/2=2.5
3/4=0.75
and so on
=================================================
In your case, you have got the answer as 8.99624
======
So, you use double.
You can also use float if you want precision upto only 6 digits.