?? function to evaluate f(1) + f(2) + ... + f(n).cpp
字號:
//
// Example 14.12. Function to evaluate f(1) + f(2) + ... + f(n)
// for a variety of functions, f, and values of positive integer n
//
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const int TRIPLE_FUN = 1;
const int SQR_FUN = 2;
const int SQRT_3X_FUN = 3;
const int QUIT = 4;
int main()
{
void menu(int& choice, int& n);
float sigma(float (*f)(int i), int n);
float triple(int i);
float sqr(int i);
float sqrt3x(int i);
float (*funPtr)(int i);
int choice; // menu choice
int n; // number of summands
float sum; // f(1) + f(2) + ... + f(n)
menu(choice, n); // priming read
while (choice != QUIT)
{
if (choice == TRIPLE_FUN)
funPtr = triple;
else if (choice == SQR_FUN)
funPtr = sqr;
else if (choice == SQRT_3X_FUN)
funPtr = sqrt3x;
cout << endl << "f(" << n << ") = "
<< fixed << showpoint
<< setprecision(2) << (*funPtr)(n) << endl;
sum = sigma(funPtr, n);
cout << "f(1) + f(2) + ... + f(" << n << ") = " << sum << endl;
menu(choice, n); // another choice
}
cout << endl << "Thank you" << endl;
return 0;
}
//
// Function to give a menu of function choices and to
// return that choice. The function also reads and returns
// the number of summands.
// Pre: none
// Post: A menu choice (choice) and a number of summands
// (n) was returned.
//
void menu(int& choice, int& n)
{
cout << "Program evaluates f(n) & f(1) + f(2) + ... + f(n)" << endl;
do
{
cout << "Choose a function" << endl;
cout << "\t1 f(x) = 3x" << endl;
cout << "\t2 f(x) = x^2" << endl;
cout << "\t3 f(x) = square root of 3x" << endl;
cout << "\t4 Quit" << endl << endl;
cout << "Your choice: ";
cin >> choice;
}
while (choice < 1 || choice > 4);
if (choice == QUIT) // no function, don't pick n
n = 0;
else // function chosen, pick n
do
{
cout << "Give a positive integer value for n: ";
cin >> n;
}
while (n < 1);
}
//
// Function to return f(1) + f(2) + ... + f(n) for
// a function to which f points and positive integer n
// Pre: n is a positive integer.
// Post: A floating point sum f(1) + f(2) + ... + f(n)
// was returned.
//
float sigma(float (*f)(int i), int n)
{
float sum = 0; // f(1) + f(2) + ... + f(n)
for (int k = 1; k <= n; ++k)
sum += (*f)(k);
return sum;
}
//
// Function to return float 3i for integer i
// Pre: i is an integer.
// Post: float 3i was returned.
//
float triple(int i)
{
return float(3 * i);
}
//
// Function to return float i^2 for integer i
// Pre: i is an integer.
// Post: float i^2 was returned.
//
float sqr(int i)
{
return float(i * i);
}
//
// Function to return float sqrt(3i) for integer i
// Pre: i is an integer.
// Post: float sqrt(3i) was returned.
//
float sqrt3x(int i)
{
return float(sqrt(3 * i));
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -