1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <iostream> #include <cmath> const double SPEED_OF_SOUND = 343.0; // Speed of sound in air at 20°C in m/s // Function to calculate the observed frequency using the Doppler effect formula double calculateDopplerEffect(double sourceFrequency, double sourceSpeed, double observerSpeed, bool movingTowards) { if (movingTowards) { return sourceFrequency * ((SPEED_OF_SOUND + observerSpeed) / (SPEED_OF_SOUND - sourceSpeed)); } else { return sourceFrequency * ((SPEED_OF_SOUND - observerSpeed) / (SPEED_OF_SOUND + sourceSpeed)); } } int main() { double sourceFrequency, sourceSpeed, observerSpeed; char direction; std::cout << "Enter the frequency of the source (Hz): "; std::cin >> sourceFrequency; std::cout << "Enter the speed of the source (m/s): "; std::cin >> sourceSpeed; std::cout << "Enter the speed of the observer (m/s): "; std::cin >> observerSpeed; std::cout << "Is the observer moving towards the source? (y/n): "; std::cin >> direction; bool movingTowards = (direction == 'y' || direction == 'Y'); double observedFrequency = calculateDopplerEffect(sourceFrequency, sourceSpeed, observerSpeed, movingTowards); std::cout << "The observed frequency is: " << |
Explanation
- Constants:
SPEED_OF_SOUND
: The speed of sound in air at 20°C, set to 343 m/s. This is the reference speed used in the Doppler effect calculations.
- calculateDopplerEffect Function:
- This function calculates the observed frequency based on whether the source and observer are moving towards or away from each other.
- Main Function:
- The program prompts the user to input the source frequency, source speed, observer speed, and whether the observer is moving towards or away from the source.
- Based on the input, the program calls
calculateDopplerEffect
to determine the observed frequency and displays the result.
Usage
- Source Frequency: The frequency of the sound emitted by the source (e.g., a siren).
- Source Speed: The speed at which the source is moving.
- Observer Speed: The speed at which the observer is moving.
- Direction: Whether the observer is moving towards or away from the source.