#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
int air=1100;
int wind=4900;
int steel=16400;
int choice;
int distance;
double time;
cout << "A) Air \nB) Water \nC) Steel \nSelect a medium for sound to travel through." << endl;
cin >> choice;
cout << "Enter a distance for sound to travel through:" << endl;
cin >> distance;
time = distance / choice;
cout << "Time traveled is:" << setprecision (4) << time;
return 0;
}
When both the divisor and dividend are of integral type, C/C++ assumes you want integer math.
When at least one of the two is of floating point type, C/C++ performs floating point arithmetic instead.
Ok that makes sense but how when i do cin how does the compiler know which if the 3 to chose? Is it by for example if the user enters a a) or is it when they type out air?
Also this program runs but I get a random 1 in the output...
If the user types out "air" the cin statement will fail. The word air cannot be converted into an integer value. cin is part of the standard template library, the keyword being template. At compile time, the compiler evaulates the cin statements and generates code that deals with each type. If the cin statement is streaming into an int the operation will fail when the user enters something that cannot be converted to an int.
Your program could result in undefined behavior because if cin fails, the variable is uninitialized which results in either garbage after the calculation or possibly a divide by zero which would cause a run-time error. The program isn't really finished so of course there is going to be weird output data. Even if the user entered a character, the math makes no sense at all.
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
int air=1100;
int wind=4900;
int steel=16400;
int n;
int choice;
int distance;
double time;
cout << "1) Air \n2) Water \n3) Steel \nSelect a medium for sound to travel through." << endl;
cin >> n;
switch(n){
case(1): choice = air;
break;
case(2): choice = wind;
break;
case(3): choice = steel;
break;
default: choice = 1;
}
cout << "Enter a distance for sound to travel through:" << endl;
cin >> distance;
time = distance / choice;
cout << "Time traveled is:" << setprecision (4) << time;
return 0;
}
A second thing is that with time = distance / choice; time will be 0.0 if choice is bigger than distance. This comes because distance and choice are integers and integer/integer with numbers behind the comma will always round to the lower full number (0.0045 => 0).
If you write it this way (distance*1.0) / choice it whould work. This way you'll have double/integer whichs result is also a double and no integer.