Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

. (5 pts) Write a program that allows the user to type a string such as exp(x),

ID: 3586854 • Letter: #

Question

. (5 pts) Write a program that allows the user to type a string such as exp(x), log(x), log10(x), pow(a, b), or sqrt(x) where x, a, and b are double-precision floating point literals. (The methods associated with these functions are listed in Table 4.2 on 121.) The program should use the printf method (page 145- 149) to output the result rounded to 4 decimal places to the right of the decimal point. For example, if the user inputs the string log10 (1000) the computed result should be 3.0000. If the user inputs the string pow(2. 5, 2) the computed result should be 6 . 2500.

Explanation / Answer

Save the below CPP code in a file, compile and run.

Enter the input as mentioned in your question like: exp(12.34),pow(123.45,1.2),..so on. You can modify the code as per your requirement.

/*******************/

/*
* MathExp.cpp
*
* Created on: 05-Oct-2017
*      Author:
*/
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
int main()
{
   double result=0.0;
   char str[20];
   cout<<"Enter the expression";
   cin>>str;
   char expr[10]={0};
   double arg=0,argb=0;
   int count=0;
   char* ptr=strtok(str,"(,)");
   while(ptr)
   {
       if(count==0)
       {
           strcpy(expr,ptr);
       }
       else if(count==1)
       {
           arg=(double)atof(ptr);
       }
       else if(count==2)
       {
           argb=(double)atof(ptr);
       }
       count++;
       ptr=strtok(NULL,"(,)");
   }
//   cout<<expr<<" "<<arg<<","<<argb<<endl;
   if(!strcmp(expr,"exp"))
       result=exp(arg);
   else if(!strcmp(expr,"log"))
       result=log(arg);
   else if(!strcmp(expr,"log10"))
           result=log10(arg);
   else if(!strcmp(expr,"pow"))
           result=pow(arg,argb);
   else if(!strcmp(expr,"sqrt"))
           result=sqrt(arg);
   else
       cout<<"Please enter correct expression"<<endl;
   cout<<"Result is: "<<result<<endl;

}