.10 .20 .15 .34 .12 .05 .12 .56 .65 .21 .98 .02 .36 .03 2. Write a C++ program n
ID: 3623017 • Letter: #
Question
.10.20
.15
.34
.12
.05
.12
.56
.65
.21
.98
.02
.36
.03
2. Write a C++ program named xxxxpa1.cpp (where xxxx is your UBIT name) that does the following:
a. Asks the user, with a message to the screen, how many numbers to read from the data file.
b. The user inputs a number with the keyboard.
c. If the number is not greater than 0 and not less than or equal to 14, the program prints an error message and continually asks the user for a new number until a number between 1 and 14 is entered. You must use a while loop to accomplish this.
d. In a for loop the program:
1. Reads a number x from the file.
2. If x is less than 0.1, the program calculates the value of f(x)=x*x+sin(x)
3. If x is less than 0.5 and greater than or equal to 0.1, the program calculates the value of f(x) = x*x + cos(x).
4. If x is greater than or equal to 0.5, the program calculates the value of f(x) = x*x + tan(x)
e. Prints the sum of the x values read and the sum of the f(x) values calculated to the screen and to a file named results.txt.
Explanation / Answer
please rate - thanks
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
int main()
{ifstream in;
ofstream out;
int n,i;
double x,fx,xsum=0,fxsum=0;
cout<<"How many numbers in your file? ";
cin>>n;
while(n<=0||n>14)
{cout<<"must be between 1 and 14! ";
cin>>n;
}
in.open("input.txt");
if(in.fail())
{ cout<<"input file did not open please check it ";
system("pause");
return 1;
}
cout<<"x f(x) ";
for(i=0;i<n;i++)
{in>>x;
if(x<.1)
fx=sin(x);
else if(x<.5)
fx=cos(x);
else
fx=tan(x);
fx+=(x*x);
cout<<x<<" "<<fx<<endl;
xsum+=x;
fxsum+=fx;
}
cout<<endl;
out.open("result.txt");
cout<<"sum of x: "<<xsum<<endl;
cout<<"sum of f(x): "<<fxsum<<endl;
out<<"sum of x: "<<xsum<<endl;
out<<"sum of f(x): "<<fxsum<<endl;
in.close();
out.close();
system("pause");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.