Board logo

標題: Help with writing python math programs [打印本頁]

作者: Intelstan    時間: 2008-7-1 08:58     標題: Help with writing python math programs

How do you write a code for calculating arithmetic and geometric mean using python?  I want to make it so that users can input as many numbers as they want to calculate.   

I only got to this far (but it's not correct):

print "This is a program that calculates arithmetic mean."
x = int( raw_input("Please enter the first number: ") )
y = int( raw_input("Please enter the second number: ") )
z = int( raw_input("Please enter the third number: ") )
print "The arithmetic mean of the three numbers is", (x+y+z)/3, "."
作者: p51dray    時間: 2008-7-1 20:50

uh use an array?

I don't know python but the general strategy is to use a dynamic array whose size increases by one as the user enters in the numbers.  
Then you just loop through the array to calculate the mean.

[ 本帖最後由 p51dray 於 2008-7-1 21:54 編輯 ]
作者: siumaibb    時間: 2008-7-2 13:00

create variables, one for the sum and one for the count, then create a loop to prompt user input...

pseudo code should be something like this:

procedure main
   double sum = 0;
   integer count = 0;
   string input = 'exit';

   loop
      input = raw_input('blah blah blah, type exit when done')
      // check input
      sum = sum + int( input )
      count = count + 1
   loop unit input = 'exit'

   if count > 0
      output sum / count
   end if

end procedure




歡迎光臨 溫哥華老友記討論區 (http://www.loyaukee.com/forum/) Powered by Discuz! 7.2