fork download
  1. // Chapter 4 - Programming Challenge #19
  2. // The Speed of Sound in Gases
  3. // This program allows the user to select a gas and enter
  4. // the amount of time sound traveled through that gas.
  5. // It then calculates and displays the distance the sound
  6. // traveled in meters.
  7.  
  8. #include <iostream>
  9. using namespace std;
  10.  
  11. int main()
  12. {
  13. // Constants for the speed of sound in each gas
  14. const double CARBON_DIOXIDE = 258.0;
  15. const double AIR = 331.5;
  16. const double HELIUM = 972.0;
  17. const double HYDROGEN = 1270.0;
  18.  
  19. // Variables for the user's choice, time, speed, and distance
  20. int choice;
  21. double time, speed, distance;
  22.  
  23. // Display the gas menu
  24. cout << "Select a gas:" << endl;
  25. cout << "1. Carbon Dioxide" << endl;
  26. cout << "2. Air" << endl;
  27. cout << "3. Helium" << endl;
  28. cout << "4. Hydrogen" << endl;
  29. cout << "Enter your choice: ";
  30. cin >> choice;
  31.  
  32. // Check that the user entered a valid menu choice
  33. if (choice < 1 || choice > 4)
  34. {
  35. cout << "Invalid choice." << endl;
  36. return 0;
  37. }
  38.  
  39. // Get the travel time from the user
  40. cout << "Enter the time in seconds: ";
  41. cin >> time;
  42.  
  43. // Check that the time is between 0 and 30 seconds
  44. if (time < 0 || time > 30)
  45. {
  46. cout << "Invalid time." << endl;
  47. return 0;
  48. }
  49.  
  50. // Determine the speed of sound for the selected gas
  51. switch (choice)
  52. {
  53. case 1:
  54. speed = CARBON_DIOXIDE;
  55. break;
  56.  
  57. case 2:
  58. speed = AIR;
  59. break;
  60.  
  61. case 3:
  62. speed = HELIUM;
  63. break;
  64.  
  65. case 4:
  66. speed = HYDROGEN;
  67. break;
  68. }
  69.  
  70. // Calculate the distance traveled
  71. distance = speed * time;
  72.  
  73. // Display the calculated distance
  74. cout << "The sound traveled " << distance
  75. << " meters." << endl;
  76.  
  77. return 0;
  78. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Select a gas:
1. Carbon Dioxide
2. Air
3. Helium
4. Hydrogen
Enter your choice: Invalid choice.