#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;
}