Question of C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Question of C++

Can you help with editing this code? Write a program that calculates the value of e ^ x using the following equation (up to three decimal places). This program will get x and the number of secret sentences n from the input. e^x= 1 + x/1! + x^2/2! +x^3/3! +..... 👇🏻👇🏻👇🏻 #include <iostream> #include <math.h> #include <bits/stdc++.h> using namespace std; int main() {     int n = 1;     double x;     cout << "Enter x: " ;     cin >> x;     cout << "Enter n: " ;     cin >> n;          int fact = 1;     for(int i = n-1; i <=n; ++i)     {         fact*=i;     }     int e;     int sum1 = 0;     int sum2;     while(n>0)     {         e = pow(x,n-1)/fact;         sum2 = sum1 + exp(x);         n++;         }              cout << fixed << setprecision(3) <<sum2;     return 0; }

18th Mar 2020, 11:49 AM
zahrad
zahrad - avatar
5 Answers
+ 3
#include <iostream> #include <iomanip> using namespace std; int main() { int n; double x; cout << "Enter x: "; cin >> x; cout << "Enter n: "; cin >> n; double sum = 1; double fact = 1; double px = 1; for(int i = 1; i < n; ++i){ px *= x; fact *= i; sum += px / fact; } cout << fixed << setprecision(3) <<sum; return 0; }
18th Mar 2020, 12:33 PM
andriy kan
andriy kan - avatar
+ 3
zahrad edited (should be < instead of <=, left after copy&paste of your code), check now
18th Mar 2020, 12:46 PM
andriy kan
andriy kan - avatar
+ 2
andriy kan Thank you for your help. fixed
18th Mar 2020, 12:50 PM
zahrad
zahrad - avatar
0
andriy kan There's a problem. When I have n = 1, the output must be 1 but not so.
18th Mar 2020, 12:45 PM
zahrad
zahrad - avatar
- 1
Condtion in for loop should be <= instead of < .
19th Mar 2020, 2:55 AM
Neetesh Koli