ผลต่างระหว่างรุ่นของ "Algo lab/templates/postfix"

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
(สร้างหน้าด้วย "<syntaxhighlight lang="cpp"> #include <iostream> #include <string> #include <iomanip> using namespace std; typedef double ValueType; struct ListNode {...")
 
แถว 1: แถว 1:
 +
'''Comments:'''
 +
 +
* Since the stack has to keep doubles, we change <tt>ValueType</tt> to <tt>double</tt>.
 +
* We use <tt>iomanip</tt> to set precision.
 +
* We use function <tt>stod</tt> to convert strings to doubles.  (s-to-d)
 +
 
<syntaxhighlight lang="cpp">
 
<syntaxhighlight lang="cpp">
 
#include <iostream>
 
#include <iostream>

รุ่นแก้ไขเมื่อ 23:35, 22 กันยายน 2564

Comments:

  • Since the stack has to keep doubles, we change ValueType to double.
  • We use iomanip to set precision.
  • We use function stod to convert strings to doubles. (s-to-d)
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

typedef double ValueType;

struct ListNode {
  ValueType val;
  ListNode* next;

  ListNode(ValueType val, ListNode* next=nullptr)
    : val(val), next(next) {}
};

ValueType pop(ListNode*& head)
{ 
  ListNode* next = head->next;
  ValueType x = head->val;
  delete head;
  head = next;

  return x; 
}

void push(ListNode*& head, ValueType x)
{
  ListNode* new_node = new ListNode(x, head);
  head = new_node;
}


int main()
{
  string buffer;

  ListNode* head = nullptr;

  do {
    cin >> buffer;
    if(buffer.at(0) == '=') {
      break;
    } else if((buffer.at(0) >= '0') && (buffer.at(0) <= '9')) {
      double val = stod(buffer);
      // *****************************
      // insert val into the top of the stack

    } else {
      // *****************************
      // buffer is an operator.
      // your code here

    }
  } while(true);
  cout << fixed << setprecision(4) << head->val << endl;
}