|
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 36 37 38 39 40 41 42 43 44 45 46 |
#include <iostream> #include <cmath> class DopplerEffect { public: DopplerEffect(double sourceFrequency, double speedOfSound) : sourceFrequency(sourceFrequency), speedOfSound(speedOfSound) {} // Calculates the observed frequency when the source and observer are moving double calculateObservedFrequency(double observerSpeed, double sourceSpeed) const { // Doppler effect formula: // f' = f * (v + vo) / (v + vs) // Where: // f' is the observed frequency // f is the source frequency // v is the speed of sound // vo is the speed of the observer (positive if moving towards the source) // vs is the speed of the source (positive if moving away from the observer) double observedFrequency = sourceFrequency * (speedOfSound + observerSpeed) / (speedOfSound + sourceSpeed); return observedFrequency; } private: double sourceFrequency; // Frequency of the source in Hz double speedOfSound; // Speed of sound in the medium (e.g., air) in m/s }; int main() { double sourceFrequency = 440.0; // Frequency of the source (e.g., a sound wave) in Hz double speedOfSound = 343.0; // Speed of sound in air at 20°C in m/s DopplerEffect doppler(sourceFrequency, speedOfSound); // User input for observer's and source's speeds double observerSpeed, sourceSpeed; std::cout << "Enter the speed of the observer (m/s, positive if moving towards the source): "; std::cin >> observerSpeed; std::cout << "Enter the speed of the source (m/s, positive if moving away from the observer): "; std::cin >> sourceSpeed; double observedFrequency = doppler.calculateObservedFrequency(observerSpeed, sourceSpeed); std::cout << "Observed Frequency: " << observedFrequency << " Hz" << std::endl; return 0; } |
Explanation
- Header Files:
<iostream>: For input and output operations.<cmath>: Included for completeness, though not used in this specific example.
- DopplerEffect Class:
- Constructor: Initializes the
sourceFrequencyandspeedOfSound. The source frequency is the frequency of the wave emitted by the source, and the speed of sound is the propagation speed of the wave through the medium. - calculateObservedFrequency(): Uses the Doppler effect formula to compute the observed frequency:
- Formula:
f' = f * (v + vo) / (v + vs)f'= observed frequencyf= source frequencyv= speed of soundvo= speed of the observer (positive if moving towards the source)vs= speed of the source (positive if moving away from the observer)
- Formula:
- Constructor: Initializes the
- main() Function:
- Creates an instance of
DopplerEffectwith a given source frequency and speed of sound. - Prompts the user for the observer’s speed and the source’s speed.
- Calculates the observed frequency using the
calculateObservedFrequency()method. - Displays the observed frequency.
- Creates an instance of