C++ HW12-2(堆疊) for WallPower

請利用堆疊儲存多項式係數,並在輸入變數值後,求出多項式之值。
參考結果如下。

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
#define NUM 100
int x;
class stack {
public:
 stack();
 void push(int);
 int pop();
 void printStack();
private:
 int array[NUM];
 int top;
};

stack::stack() {
 top = -1;
}
void stack::push(int n)
{
 if (top == NUM - 1) {
  cout << "stack is full!";
  exit(1);
 }
 array[++top] = n;
}
int stack::pop()
{
 if (top == -1) {
  cout << "stack is empty!!";
  exit(1);
 }
 return array[top--];
}
void stack::printStack()
{
 int i;
 if (top == -1) {
  cout << "stack is empty!!\n";
 }
 else {
  int sum = 0;
  for (i = top; i >= 1; i--)
   sum += pow(x, i) * pop();
  sum += pop();
  cout << sum << endl;
 }
}
int main(void)
{
 int choice = 0, input;
 stack S1;
 cout << "請輸入多項式之常數項係數:";
 cin >> input;
 S1.push(input);
 while (true)
 {
  cout << "請輸入多項式之高一項係數(結束時請輸入-999):";
  cin >> input;
  if (input == -999)
   break;
  S1.push(input);
 }
 cout << "請輸入變數之值:";
 cin >> x;
 cout << "f(" << x << ") = ";
 S1.printStack();
 system("pause");
 return 0;
}

留言

這個網誌中的熱門文章

UVA 11321 Java