#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

// Read one whole line so a failed conversion cannot trap the input stream.
bool readNumber(const std::string& prompt, double& value, double low, double high) {
    std::string line;
    while (std::cout << prompt && std::getline(std::cin, line)) {
        std::istringstream input(line);
        char extra = '\0';
        if (input >> value && !(input >> extra) && std::isfinite(value)
            && value >= low && value <= high) {
            return true;
        }
        std::cout << "Enter a finite number in [" << low << ", " << high << "].\n";
    }
    std::cerr << "Input ended before a valid number was supplied.\n";
    return false;
}

double capacitorVoltage(double supplyVolts, double timeSeconds, double tauSeconds) {
    // expm1(z) computes exp(z)-1 accurately even when z is close to zero.
    return -supplyVolts * std::expm1(-timeSeconds / tauSeconds);
}

int main() {
    double resistanceOhms = 0.0, capacitanceMicrofarads = 0.0, supplyVolts = 0.0;
    if (!readNumber("Resistance (ohms): ", resistanceOhms, 1e-3, 1e9)
        || !readNumber("Capacitance (microfarads): ", capacitanceMicrofarads, 1e-6, 1e6)
        || !readNumber("Supply voltage (V): ", supplyVolts, 0.0, 1e6)) return 1;
    const double capacitanceFarads = capacitanceMicrofarads * 1e-6;
    const double tauSeconds = resistanceOhms * capacitanceFarads;
    std::cout << std::fixed << std::setprecision(9)
              << "Time constant (s): " << tauSeconds << '\n'
              << "multiple time_s voltage_V\n";
    for (int multiple = 0; multiple <= 5; ++multiple) {
        const double timeSeconds = multiple * tauSeconds;
        std::cout << multiple << ' ' << timeSeconds << ' '
                  << capacitorVoltage(supplyVolts, timeSeconds, tauSeconds) << '\n';
    }
}
