Hướng dẫn how to input negative numbers in python - cách nhập số âm trong python

Tôi là một sinh viên trong một khái niệm về lớp lập trình. Phòng thí nghiệm được điều hành bởi một TA và hôm nay trong phòng thí nghiệm, anh ấy đã cho chúng tôi một chương trình nhỏ đơn giản thực sự để xây dựng. Đó là một nơi mà nó sẽ nhân lên bằng cách bổ sung. Dù sao, anh ấy đã sử dụng chúng tôi tuyệt đối để tránh phá vỡ prog với những tiêu cực. Tôi đã đánh nó thật nhanh và sau đó tranh luận với anh ta trong 10 phút rằng đó là toán học tồi. Đó là, 4 * -5 không bằng 20, nó bằng -20. Anh ấy nói rằng anh ấy thực sự không quan tâm đến điều đó và dù sao thì anh ấy cũng sẽ quá khó để làm cho Prog xử lý những tiêu cực. Vì vậy, câu hỏi của tôi là làm thế nào để tôi đi về điều này.

Đây là prog tôi đã chuyển vào:

#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

Tôi muốn làm điều đó mà không cần tuyệt đối, nhưng mỗi khi tôi nhập số âm, tôi sẽ nhận được một con ngỗng lớn. Tôi biết có một số cách đơn giản để làm điều đó, tôi không thể tìm thấy nó.

Hướng dẫn how to input negative numbers in python - cách nhập số âm trong python

hỏi ngày 16 tháng 3 năm 2010 lúc 2:37Mar 16, 2010 at 2:37

3

Có lẽ bạn sẽ hoàn thành điều này với một cái gì đó với hiệu ứng của

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

hoặc có thể

a * b

Đã trả lời ngày 16 tháng 3 năm 2010 lúc 2:52Mar 16, 2010 at 2:52

Hướng dẫn how to input negative numbers in python - cách nhập số âm trong python

Mike Grahammike GrahamMike Graham

71.3K14 Huy hiệu vàng98 Huy hiệu bạc129 Huy hiệu đồng14 gold badges98 silver badges129 bronze badges

1

Quá khó? TA của bạn là ... tốt, cụm từ có thể sẽ khiến tôi bị cấm. Dù sao, hãy kiểm tra xem

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
0 có âm không. Nếu nó được nhân
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
1 với
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
2 và làm
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
3. Sau đó làm vòng lặp.

Đã trả lời ngày 16 tháng 3 năm 2010 lúc 2:50Mar 16, 2010 at 2:50

2

ABS () trong điều kiện là cần thiết, vì, tốt, nó kiểm soát số lần lặp (làm thế nào bạn sẽ xác định một số lần lặp âm?). Bạn có thể sửa nó bằng cách đảo ngược dấu hiệu của kết quả nếu

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
0 là âm.

Vì vậy, đây là phiên bản sửa đổi của mã của bạn. Lưu ý tôi đã thay thế vòng lặp trong khi một vòng sạch hơn cho vòng lặp.

#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

Đã trả lời ngày 16 tháng 3 năm 2010 lúc 3:03Mar 16, 2010 at 3:03

Slackerslackerslacker

2.13211 Huy hiệu bạc10 Huy hiệu đồng11 silver badges10 bronze badges

Hãy thử điều này trên TA của bạn:

# 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

output:

3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129

Đã trả lời ngày 16 tháng 3 năm 2010 lúc 4:13Mar 16, 2010 at 4:13

John Machinjohn MachinJohn Machin

79,7K11 Huy hiệu vàng138 Huy hiệu bạc184 Huy hiệu đồng11 gold badges138 silver badges184 bronze badges

3

Làm thế nào về một cái gì đó như vậy? .
Notes:

  • Hàm abs () chỉ được sử dụng cho thủ thuật tối ưu hóa. Đoạn này có thể được gỡ bỏ hoặc mã hóa lại.
  • Logic kém hiệu quả hơn vì chúng tôi đang thử nghiệm dấu hiệu A và B với mỗi lần lặp (giá phải trả để tránh cả toán tử ABS () và phép nhân)

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

Đã trả lời ngày 16 tháng 3 năm 2010 lúc 3:13Mar 16, 2010 at 3:13

MJVMJVmjv

71.4K14 Huy hiệu vàng111 Huy hiệu bạc156 Huy hiệu đồng14 gold badges111 silver badges156 bronze badges

4

Cảm ơn tất cả mọi người, tất cả các bạn đã giúp tôi học hỏi rất nhiều. Đây là những gì tôi đã đưa ra bằng cách sử dụng một số đề xuất của bạn

#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

Cảm ơn mọi người vì tất cả sự giúp đỡ.

Đã trả lời ngày 16 tháng 3 năm 2010 lúc 23:42Mar 16, 2010 at 23:42

dman762000dman762000dman762000

Huy hiệu vàng 18111 gold badge1 silver badge6 bronze badges

5

Hãy thử làm điều này:

num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
ans = num1*num2


if num1 > 0 or num2 > 0:
    print(ans)

elif num1 > 0 and num2 < 0 or num1 < 0 and num1 > 0:
    print("-"+ans)

elif num1 < 0 and num2 < 0:
    print("Your product is "+ans)
else:
    print("Invalid entry")

Đã trả lời ngày 2 tháng 12 năm 2021 lúc 2:46Dec 2, 2021 at 2:46

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 ()  

Đã trả lời ngày 10 tháng 11 năm 2014 lúc 20:34Nov 10, 2014 at 20:34

KitiyokitiyoKitiyo

11 Huy hiệu vàng2 Huy hiệu bạc3 Huy hiệu đồng1 gold badge2 silver badges3 bronze badges

1

Làm thế nào để bạn viết một số âm trong Python?

Trong Python, các số dương có thể được thay đổi thành số âm với sự trợ giúp của phương thức được xây dựng được cung cấp trong thư viện Python có tên ABS (). Khi ABS () được sử dụng, nó chuyển đổi số âm thành dương. Tuy nhiên, khi -abs () được sử dụng, thì một số dương có thể được thay đổi thành số âm.abs (). When abs () is used, it converts negative numbers to positive. However, when -abs () is used, then a positive number can be changed to a negative number.

Làm thế nào để bạn nhập một danh sách tiêu cực vào Python?

int () có thể chuyển đổi một chuỗi thành một số nguyên.Bản đồ (int, ...) trả về một số lượng có thể áp dụng int () cho mỗi "từ" của đầu vào người dùng. Cuộc gọi cuối cùng đến danh sách () sẽ biến số lượng khác nhau thành một danh sách.Điều này cũng nên xử lý các số âm là tốt.map(int, ...) returns an iterable which applies int() to each "word" of the user input. The final call to list() will turn the iterable to a list. This should handle negative numbers as well.

Làm thế nào để Python lưu trữ số âm?

Các số âm được viết với một số hàng đầu thay vì số 0 hàng đầu.Vì vậy, nếu bạn chỉ sử dụng 8 bit cho các số bổ sung twos của mình, thì bạn sẽ xử lý các mẫu từ "00000000" đến "01111111" như toàn bộ số từ 0 đến 127 và dự trữ "1xxxxxxxx" để viết số âm.. So if you are using only 8 bits for your twos-complement numbers, then you treat patterns from "00000000" to "01111111" as the whole numbers from 0 to 127, and reserve "1xxxxxxx" for writing negative numbers.

Số âm có thể là số nguyên trong Python không?

Một số nguyên, thường được viết tắt thành int, là một số toàn bộ (dương, âm hoặc bằng không).Vì vậy, 7, 0, -11, 2 và 5 là số nguyên.3.14159, 0,0001, 11.11111 và thậm chí 2.0 không phải là số nguyên, chúng là nổi trong Python.7 , 0 , -11 , 2 , and 5 are integers. 3.14159 , 0.0001 , 11.11111 , and even 2.0 are not integers, they are floats in Python.