Postfix Calculator – RPN Calculator
Most beginner calculator programs stop at basic arithmetic and never feel like the real thing. Going a step beyond that, I made a program that can also compute values such as sin(30) and log(18), and even nest them within one another.
I wrote the program in C++, since the STL lets me put it together quickly, leaning on its queue and stack data structures. The idea is to walk through the string expression the user enters, one token at a time: if it is a number, it goes onto the stack, and if it is an operator, it waits for its turn in the operation order. That is really just converting the expression into RPN (reverse Polish notation) format, an algorithm you can see on Wikipedia.
From there, by treating the functions in the expression as operators too, I applied that same algorithm and computed the results with the help of the queue. The last element left in the queue is the final answer, so that is what I printed to the screen.
You can find the code at my GitHub address. https://github.com/ffahri/RPNCalculator
– Turkish Version –
Postfix Hesap Makinesi – RPN Calculator
Çoğu başlangıç seviyesi hesap makinesi programı temel dört işlemde kalır ve gerçeğine pek benzemez. Bundan bir adım öteye geçerek, sin(30), log(18) gibi değerleri de hesaplayabilen ve hatta bunları iç içe kullanabilen bir program yaptım.
Programı C++ ile yazdım, çünkü STL sayesinde hızlı bir şekilde gerçekleştirebiliyorum; onun kuyruk ve yığın veri yapılarından yararlandım. Fikir şu: kullanıcının girdiği string ifadeyi token token sırasıyla geziyorum. Eğer sayı ise yığına aktarıyor, operatörse işlem sırasını bekliyor. Yani aslında ifadeyi TPN (ters Polonyalı notasyonu – reverse Polish notation) formatına çeviriyorum; bu algoritmayı vikipediden görebilirsiniz.
Buradan sonra string ifadesindeki fonksiyonları da birer operatör olarak düşünüp aynı algoritmayı kullandım ve sonuçları kuyruk yardımıyla hesapladım. Kuyrukta kalan son eleman nihai sonucum olduğu için onu ekrana yazdırdım.
Kodları github adresimde bulabilirsiniz. https://github.com/ffahri/RPNCalculator