first_num = int(input("First number >>> "))
second_num = int(input("Second number >>> "))
if first_num >= second_num:
diff = first_num - second_num
else:
diff = second_num - first_num
print(f"The absolute difference of {first_num} and {second_num} is {diff}.")
uj5u.com熱心網友回復:
我假設這是 Python,雖然你還不清楚。
first_num = int(input("First number >>>"))
second_num = int(input("Second number >>>"))
# Here is the ternary part: Python doesn't have an explicit ternary
# operator like C/C , but does have this more compact if/else syntax
# which acts like one
difference = (first_num - second_num) if (first_num > second_num) else (second_num - first_num)
printf(f'The absolute difference of {first_num} and {second_num} is {difference}')
uj5u.com熱心網友回復:
這是一個相當簡單的方法,因為它遵循以下形式something if condition else something_else:
diff = first_num - second_num if first_num >= second_num else second_num - first_num
但是,老實說,如果你想要絕對值,只需使用以下abs()函式:
diff = abs(first_num - second_num)
uj5u.com熱心網友回復:
為此,您根本不需要任何三元邏輯,因為 Python 有一個內置abs()函式,它將回傳絕對值:
first_num = int(input("First number >>> "))
second_num = int(input("Second number >>> "))
print(f"The absolute difference of {first_num} and {second_num} is {abs(first_num - second_num)}")
uj5u.com熱心網友回復:
您可以通過使用“if”陳述句來使用三元運算子。
在您的代碼中,
diff = first_num-second_num if first_num>=second_num else second_num-first_num
格式如下,
diff = (exp1) if (condition) else (exp2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/442519.html
