fork download
  1. //Zachary Abdollahi CS1A Chapter 4, P. 224, #19
  2. //
  3. /*******************************************************************************
  4.  *
  5.  * CALCULATE SPEED OF SOUND IN GASES
  6.  *
  7.  *______________________________________________________________________________
  8.  * This program displays a menu of four gases. The user selects a gas and enters
  9.  * the time it took sound to travel through it. The program then calculates and
  10.  * displays the distance the sound traveled, using each gas's speed of sound.
  11.  *
  12.  * INPUT
  13.  * choice : Menu selection for the gas (1-4)
  14.  * seconds : Time in seconds for sound to travel (0-30)
  15.  *
  16.  * OUTPUT : Distance sound traveled, in meters
  17.  *
  18.  ******************************************************************************/
  19. #include <iostream>
  20. #include <limits>
  21. using namespace std;
  22. int main()
  23. {
  24. int choice; //INPUT - Menu selection for the gas (1-4)
  25. double seconds; //INPUT - Time in seconds for the sound to travel
  26. double speed; //Speed of sound for the selected gas
  27. double distance; //OUTPUT - Distance sound traveled, in meters
  28.  
  29. // Display menu
  30. cout << "Speed of Sound Calculator" << endl;
  31. cout << "1. Carbon Dioxide" << endl;
  32. cout << "2. Air" << endl;
  33. cout << "3. Helium" << endl;
  34. cout << "4. Hydrogen" << endl;
  35. cout << "Enter your choice: ";
  36. cin >> choice;
  37.  
  38. // Validate menu choice
  39. while (cin.fail() || choice < 1 || choice > 4)
  40. {
  41. cin.clear();
  42. cin.ignore(numeric_limits<streamsize>::max(), '\n');
  43. cout << "Invalid choice. Please enter a number 1-4: ";
  44. cin >> choice;
  45. }
  46.  
  47. // Assign speed based on menu choice using a switch statement
  48. switch (choice)
  49. {
  50. case 1:
  51. speed = 258.0;
  52. break;
  53. case 2:
  54. speed = 331.5;
  55. break;
  56. case 3:
  57. speed = 972.0;
  58. break;
  59. case 4:
  60. speed = 1270.0;
  61. break;
  62. }
  63.  
  64. // Get and validate the number of seconds
  65. cout << "Enter the number of seconds: ";
  66. cin >> seconds;
  67.  
  68. while (cin.fail() || seconds < 0 || seconds > 30)
  69. {
  70. cin.clear();
  71. cin.ignore(numeric_limits<streamsize>::max(), '\n');
  72. cout << "Invalid time. Please enter a value between 0 and 30 seconds: ";
  73. cin >> seconds;
  74. }
  75.  
  76. // Calculate and display the distance
  77. distance = speed * seconds;
  78. cout << "The sound source was " << distance << " meters away." << endl;
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 0s 5316KB
stdin
2
5
stdout
Speed of Sound Calculator
1. Carbon Dioxide
2. Air
3. Helium
4. Hydrogen
Enter your choice: Enter the number of seconds: The sound source was 1657.5 meters away.