Operating System - HP-UX
1752808 Members
6015 Online
108789 Solutions
New Discussion

Adding value of 4 numbers , with dc

 
rveri-admin
Frequent Advisor

Adding value of 4 numbers , with dc

Hi Experts,

 

Wondering how to add value of multiple numbers with dc (Desk Calculator) , as no much help given in the manual.

It is working for 2 numbers:

 

Example:

 

$ echo "2 3 + p" | dc

$ 5

 

But this is not working:

$ echo "6 2 3 4 + p" | dc
7

 

 

Any Idea, whats wrong.or what I am missing.

 

Thanks,


 

5 REPLIES 5
rveri-admin
Frequent Advisor

Re: Adding value of 4 numbers , with dc

Any one ,..any update please..This is an old program but hope some one has the answer.

 

 

 

 

Matti_Kurkela
Honored Contributor

Re: Adding value of 4 numbers , with dc

"dc" is a RPN calculator, i.e. a stack-based calculator.

Numbers are pushed onto a stack, then operations take an appropriate number of parameters from the stack, operate on them and leave the result on top of the stack.

 

Your command:

$ echo "6 2 3 4 + p" | dc

would first push all four numbers to the stack, then take the last 2 numbers, calculate their sum and push the result to the stack (at this point the stack would be "6 2 7") and then print the top-most number in the stack.

 

If you want the sum of all 4 numbers, you should do:

$ echo "6 2 3 4 + + + p" | dc

The first + calculates "3 + 4", after this calculation the stack is "6 2 7".

The second + calculates "2 + 7", after this the stack is "6 9".

The third + calculates "6 + 9", after this the stack is "15".

The "p" prints "15", the top-most (and now only) value in the stack.

 

Another way of achieving the same result would be:

$ echo "6 2 + 3 + 4 + p" | dc

MK
rveri-admin
Frequent Advisor

Re: Adding value of 4 numbers , with dc

MK,

Thanks a lot , it works,  and thanks for the nice and clear explanation .

 

# echo "6 2 3 4 + + + p" | dc

15

-----

 

 

 

The other one : # echo "6 2 + 3 + 4 + p" | dc

I hope in this case , the stack calculates  6 & 2   first ,   = 8 ,

Then 8  & 3 = 11

Then 11 & 4 = 15

 

Hope I understood correct for the 2nd solution.

 

 

 

 

Also if you explain how the ( ) works in dc to keep border of the formula or calculations it will be great.

Like :   ((5*3)+2(5/2)) ^ 2 +  100

 

Thanks a lot for the help and your time.

Dennis Handly
Acclaimed Contributor

Re: Adding value of 4 numbers, with dc

>explain how the ( ) works in dc to keep order of the formula or calculations
>Like:   ((5*3)+2(5/2)) ^ 2 +  100

 

There seems to be no stinkin' parenthesis in dc(1), nor does a RPN calculator need them.

You need to brush up on your syntax directed translation skills and convert it to:

5 3 * 2 5 2 / * + 2 ^ 100 +

 

Or install gdb and use the C mode calculator there.

Matti_Kurkela
Honored Contributor

Re: Adding value of 4 numbers , with dc

You got it exactly, and Dennis already converted your more complicated calculation into RPN format for you.

MK