fork download
  1. //Maxwell Brewer CS1A Chapter 4, P. 224, #19
  2. //
  3. /***************************************************************
  4.  *
  5.  * CALCULATE SOUND SPEED
  6.  * ________________________________________________
  7.  *
  8.  * This program will take user input to determine
  9.  * the distance of sound traveling through a particular gas
  10.  * by using a switch statement.
  11.  * _____________________________________________
  12.  * INPUT
  13.  *
  14.  * environment, distance, time
  15.  *
  16.  * OUTPUT
  17.  *
  18.  * distance
  19.  *
  20.  ***************************************************************/
  21.  
  22. #include <iostream>
  23. #include <iomanip>
  24. #include <string>
  25.  
  26. using namespace std;
  27.  
  28. int main() {
  29.  
  30. // Initialization
  31. int environment;
  32. double distance;
  33. double time;
  34.  
  35. // Display input prompts
  36. cout << "In what environment is the sound travelling in?\n";
  37. cout << "1. Carbon Dioxide\n2. Air\n3. Helium\n4. Hydrogen\n";
  38. cout << "Enter 1, 2, 3 or 4:\n";
  39. cin >> environment;
  40.  
  41. cout << "How many seconds did it take? (0-30)\n";
  42. cin >> time;
  43.  
  44. // Output
  45. if(time >= 0 && time <=30){
  46. switch (environment){
  47. case 1:
  48. distance = time * 258.0;
  49. break;
  50. case 2:
  51. distance = time * 331.5;
  52. break;
  53. case 3:
  54. distance = time * 972.0;
  55. break;
  56. case 4:
  57. distance = time * 1270.0;
  58. break;
  59. default:
  60. //display error message for invalid environment
  61. //input
  62. cout << "Please enter an available environment!\n";
  63. break;
  64. }
  65. }
  66. else{
  67. //display error message for negative distances
  68. cout << "Please enter a time within given range!\n";
  69. }
  70.  
  71. //display on screen output message
  72. cout << "The distance from the source is ";
  73. cout << distance << " meters.\n";
  74.  
  75. return 0;
  76. }
Success #stdin #stdout 0.01s 5272KB
stdin
4
25
stdout
In what environment is the sound travelling in?
1. Carbon Dioxide
2. Air
3. Helium
4. Hydrogen
Enter 1, 2, 3 or 4:
How many seconds did it take? (0-30)
The distance from the source is 31750 meters.