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

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

  1. #include <iostream>
  2. #include <stdlib.h>
  3. #include <string>
  4. using namespace std;
  5. #define NUM 100
  6. int x;
  7. class stack {
  8. public:
  9. stack();
  10. void push(int);
  11. int pop();
  12. void printStack();
  13. private:
  14. int array[NUM];
  15. int top;
  16. };
  17.  
  18. stack::stack() {
  19. top = -1;
  20. }
  21. void stack::push(int n)
  22. {
  23. if (top == NUM - 1) {
  24. cout << "stack is full!";
  25. exit(1);
  26. }
  27. array[++top] = n;
  28. }
  29. int stack::pop()
  30. {
  31. if (top == -1) {
  32. cout << "stack is empty!!";
  33. exit(1);
  34. }
  35. return array[top--];
  36. }
  37. void stack::printStack()
  38. {
  39. int i;
  40. if (top == -1) {
  41. cout << "stack is empty!!\n";
  42. }
  43. else {
  44. int sum = 0;
  45. for (i = top; i >= 1; i--)
  46. sum += pow(x, i) * pop();
  47. sum += pop();
  48. cout << sum << endl;
  49. }
  50. }
  51. int main(void)
  52. {
  53. int choice = 0, input;
  54. stack S1;
  55. cout << "請輸入多項式之常數項係數:";
  56. cin >> input;
  57. S1.push(input);
  58. while (true)
  59. {
  60. cout << "請輸入多項式之高一項係數(結束時請輸入-999):";
  61. cin >> input;
  62. if (input == -999)
  63. break;
  64. S1.push(input);
  65. }
  66. cout << "請輸入變數之值:";
  67. cin >> x;
  68. cout << "f(" << x << ") = ";
  69. S1.printStack();
  70. system("pause");
  71. return 0;
  72. }

留言

這個網誌中的熱門文章

C# 井字遊戲