15

私はプログラミングクラスの概念の学生です。ラボは TA によって運営されており、今日ラボで彼は構築するための非常にシンプルな小さなプログラムを提供してくれました。足し算で掛け算するものでした。とにかく、彼は私たちに絶対を使用して、ネガでプログラムを壊さないようにしました. 私はすぐにそれをかき立て、それから彼と10分間、それは悪い数学だと主張しました. 4 * -5 は 20 ではなく、-20 です。彼は本当にそれを気にしないし、とにかくプログにネガを処理させるのは難しすぎるだろうと言った. だから私の質問は、これについてどうすればよいかということです。

これが私が提出したプログラムです:

#get user input of numbers as variables

numa, numb = input("please give 2 numbers to multiply seperated with a comma:")

#standing variables
total = 0
count = 0

#output the total
while (count< abs(numb)):
    total = total + numa
    count = count + 1

#testing statements
if (numa, numb <= 0):
    print abs(total)
else:
    print total

絶対値なしでやりたいのですが、負の数を入力するたびに大きなガチョウができます。それを行う簡単な方法があることは知っていますが、それを見つけることができません。

4

8 に答える 8

7

おそらくあなたはこれを何かの効果で達成するでしょう

text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
a = int(split_text[0])
b = int(split_text[1])
# The last three lines could be written: a, b = map(int, text.split(','))
# but you may find the code I used a bit easier to understand for now.

if b > 0:
    num_times = b
else:
    num_times = -b

total = 0
# While loops with counters basically should not be used, so I replaced the loop 
# with a for loop. Using a while loop at all is rare.
for i in xrange(num_times):
    total += a 
    # We do this a times, giving us total == a * abs(b)

if b < 0:
    # If b is negative, adjust the total to reflect this.
    total = -total

print total

または多分

a * b
于 2010-03-16T02:52:30.897 に答える
4

あまりにもハード?あなたのTAは...まあ、そのフレーズはおそらく私を禁止するでしょう。numbとにかく、マイナスかどうかを確認してください。それからそれが掛けnumaられるならば、-1そしてしなさいnumb = abs(numb)。次に、ループを実行します。

于 2010-03-16T02:50:30.387 に答える
3

while 条件の abs() が必要なのは、反復回数を制御するためです (負の反復回数をどのように定義しますか?)。numbが負の場合は、結果の符号を反転することで修正できます。

したがって、これはコードの修正版です。while ループをよりクリーンな for ループに置き換えたことに注意してください。

#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")

#standing variables
total = 0

#output the total
for count in range(abs(numb)):
    total += numa

if numb < 0:
    total = -total

print total
于 2010-03-16T03:03:16.617 に答える
1

あなたのTAでこれを試してください:

# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)

for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
    print numa, numb,
    accum = 0
    negate = False
    if numa < 0:
        negate = True
        numa = -numa
    while numa:
        if numa & 1:
            accum += numb
        numa >>= 1
        numb <<= 1
    if negate:
        accum = -accum
    print accum

出力:

3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129
于 2010-03-16T04:13:00.487 に答える
0

そのようなものはどうですか?(abs() も乗算も使用しません)
注:

  • abs() 関数は、最適化のトリックにのみ使用されます。このスニペットは、削除または再コーディングできます。
  • 各反復で a と b の符号をテストしているため、ロジックの効率が低下します (abs() と乗算演算子の両方を回避するために支払う代償)

def multiply_by_addition(a, b):
""" School exercise: multiplies integers a and b, by successive additions.
"""
   if abs(a) > abs(b):
      a, b = b, a     # optimize by reducing number of iterations
   total = 0
   while a != 0:
      if a > 0:
         a -= 1
         total += b
      else:
         a += 1
         total -= b
   return total

multiply_by_addition(2,3)
6
multiply_by_addition(4,3)
12
multiply_by_addition(-4,3)
-12
multiply_by_addition(4,-3)
-12
multiply_by_addition(-4,-3)
12
于 2010-03-16T03:13:52.677 に答える
0

皆さんありがとう、皆さんは私が多くのことを学ぶのを助けてくれました。これは私があなたの提案のいくつかを使用して思いついたものです

#this is apparently a better way of getting multiple inputs at the same time than the 
#way I was doing it
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
numa = int(split_text[0])
numb = int(split_text[1])

#standing variables
total = 0

if numb > 0:
    repeat = numb
else:
    repeat = -numb

#for loops work better than while loops and are cheaper
#output the total
for count in range(repeat):
    total += numa


#check to make sure the output is accurate
if numb < 0:
    total = -total


print total

みんな助けてくれてありがとう。

于 2010-03-16T23:42:41.590 に答える
-1
import time

print ('Two Digit Multiplication Calculator')
print ('===================================')
print ()
print ('Give me two numbers.')

x = int ( input (':'))

y = int ( input (':'))

z = 0

print ()


while x > 0:
    print (':',z)
    x = x - 1
    z = y + z
    time.sleep (.2)
    if x == 0:
        print ('Final answer: ',z)

while x < 0:
    print (':',-(z))
    x = x + 1
    z = y + z
    time.sleep (.2)
    if x == 0:
        print ('Final answer: ',-(z))

print ()  
于 2014-11-10T20:34:49.070 に答える