In: Computer Science
The formula used to calculate the density of a substance is mass divided by volume. It is expressed as d = m/v. Ask users for the mass and volume of a substance and calculate the density for them.
Output:
Enter the mass of a substance in grams (integers only): [assume
user inputs 10]
Enter the volume of a substance in milliliters (integers only):
[assume user inputs 4]
The density of your substance is 2.5
Solve in C++.
Solution:
Explanation :
In this C++ program to calculate the density of the substance.We have taken 2 variables mass and volume of integer datatype and 1 variable density of type float to store the result in floating point number.
First the user have to enter the values of mass and volume of integer type only and after that we will use the formula of density= mass/volume to calulate the result.But to get the density in floating point number we have to typecast explicitly to get a floating point result.So after the typecasted formula will be
density = float(mass)/float(volume). And at last print the result by using density.
Program Code: Comments are provided in the code to better understanding.
#include <iostream>
using namespace std;
int main()
{ int mass,volume;
float density;
//to input mass from user
cout<<"Enter
the mass of the substance in grams :" ;
cin>>mass;
//to input volume from user
cout<<"Enter the volume of the substance in mililitres :"
;
cin>>volume;
//formula to calculate density
//typecasted explicitly to get a floating point
number
density = float(mass)/float(volume);
//to print result
cout<<"The density of your substance is
:"<<density;
return 0;
}
Programming and Output Screenshot : Programming screenshot is provided to get a better understanding at the code indentation.
Thanks.I hope the code and explanations are clear.Please VOTE UP ;)