문제

저는 프로그래밍 수업 개념을 가진 학생입니다. 이 실험실은 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

나는 절대없이 그것을하고 싶지만, 음수를 입력 할 때마다 큰 뚱뚱한 구스그를 얻습니다. 나는 그것을 할 수있는 몇 가지 간단한 방법이 있다는 것을 알고 있습니다. 나는 그것을 찾을 수 없습니다.

도움이 되었습니까?

해결책

아마도 당신은

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

다른 팁

너무 열심히? 당신의 TA는 ... 글쎄, 문구는 아마도 금지 될 것입니다. 어쨌든, 확인하십시오 numb 부정적입니다. 곱하면 곱하십시오 numa ~에 의해 -1 그리고 그렇게 numb = abs(numb). 그런 다음 루프를하십시오.

ABS ()는 반복 횟수를 제어하기 때문에 () 조건이 필요합니다 (음수의 반복을 어떻게 정의 할 수 있습니까?). 결과의 부호를 반전시켜 수정할 수 있습니다. numb 부정적입니다.

그래서 이것은 코드의 수정 된 버전입니다. 참고 나는 while 루프를 루프 클리너로 교체했다.

#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

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

그런 건 어때? (abs () 또는 mulitiplication을 사용하지 않음)
메모:

  • 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

모두 감사합니다. 여러분 모두 내가 많은 것을 배우도록 도와주었습니다. 이것이 제가 귀하의 제안 중 일부를 사용하여 생각한 것입니다.

#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

모두에게 도움을 주셔서 감사합니다.

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 ()  
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top