fork download
  1. #include<fstream>
  2. #include<iostream>
  3. #include<cmath>
  4. #include<iomanip>
  5.  
  6. using namespace std;
  7.  
  8. // Using global streams as in your original code
  9. ofstream outputcharge("rcdc_charge.txt");
  10. ofstream outputdis("rcdc_discharge.txt");
  11.  
  12. class rcdc {
  13. float r, c, ti, tf, qc, ic, id, qce, qde, qo, qd, t, h;
  14. int i, n;
  15.  
  16. public:
  17. void getdatac();
  18. void calculatec();
  19. };
  20.  
  21. void rcdc::getdatac() {
  22. cout << "Enter the value of resistance (r) and capacitance (c): ";
  23. cin >> r >> c;
  24. cout << "\nEnter initial time, final time, and step size (h): ";
  25. cin >> ti >> tf >> h;
  26.  
  27. n = (tf - ti) / h;
  28. t = ti;
  29. qce = 0; // Analytical starting charge
  30. qo = 3; // Maximum charge (Q0)
  31. qde = qo; // Starting charge for discharge
  32.  
  33. // Writing headers to files
  34. outputcharge << "Time\tCharge(qc)\tCharge_Euler(qce)" << endl;
  35. outputdis << "Time\tCharge(qd)\tCharge_Euler(qde)" << endl;
  36. }
  37.  
  38. void rcdc::calculatec() {
  39. for (i = 1; i <= n; i++) {
  40. t = t + h;
  41.  
  42. // --- Charging Circuit Calculations ---
  43. // Formula: q = Q0 * (1 - exp(-t/RC))
  44. qc = qo * (1.0 - exp(-t / (r * c)));
  45.  
  46. // Current: I = (Q0/RC) * exp(-t/RC)
  47. ic = (qo / (r * c)) * exp(-t / (r * c));
  48.  
  49. // Numerical approximation (Euler Method)
  50. qce = qce + (h * ic);
  51.  
  52. // --- Discharging Circuit Calculations ---
  53. // Formula: q = Q0 * exp(-t/RC)
  54. qd = qo * exp(-t / (r * c));
  55.  
  56. // Current: Id = -dq/dt = (Q0/RC) * exp(-t/RC)
  57. id = (qo / (r * c)) * exp(-t / (r * c));
  58.  
  59. // Numerical approximation (Euler Method)
  60. qde = qde - (h * id);
  61.  
  62. // Writing data to files
  63. outputcharge << t << "\t" << qc << "\t" << qce << endl;
  64. outputdis << t << "\t" << qd << "\t" << qde << endl;
  65. }
  66.  
  67. cout << "\nSimulation complete. Data saved to .txt files." << endl;
  68. }
  69.  
  70. int main() {
  71. rcdc x;
  72. x.getdatac();
  73. x.calculatec();
  74.  
  75. outputcharge.close();
  76. outputdis.close();
  77.  
  78. return 0;
  79. }
  80.  
Success #stdin #stdout 0.01s 5324KB
stdin
Standard input is empty
stdout
Enter the value of resistance (r) and capacitance (c): 
Enter initial time, final time, and step size (h): 
Simulation complete. Data saved to .txt files.