-4

私は次のことをしようとしています:

3 つの数値を読み取り、それらがすべて同じ場合は「すべて同じ」、すべて異なる場合は「すべて異なる」、それ以外の場合は「どちらでもない」と出力するプログラムを作成します。

プログラムは、3 つの入力ステートメントを介して 3 つの整数を要求する必要があります。if、elif、else の組み合わせを使用して、この問題に必要なアルゴリズムを実装します。

ただし、すべて同じ整数を入力すると、「すべて同じ」と「どちらでもない」の両方が得られます。「どちらでもない」セクションが正しくなるようにするにはどうすればよいですか?

x=input('enter an integer:') 
y=input('enter an integer:') 
z=input('enter an integer:') 
if x==y and y==z: print('all the same') 
if not x==y and not y==z: print('all different') 
if x==y or y==z or z==x: print('neither')
4

2 に答える 2

0

ここでの問題は、ifケースごとに使用することです。これは、何があってもすべてのケースが評価され、複数のケースが true になる可能性があることを意味します。

たとえば、3 つの変数がすべて 1 の場合、ケースは次のように評価されます。

>>> x = 1
>>> y = 1
>>> z = 1
>>> if x == y and y == z: print("all the same")

all the same
>>> if not x == y and not y == z: print("all different")

>>> if x == y or y == z or z == x: print('neither')

neither
>>> 

elif(else if) とelse(フロー制御のドキュメントを参照)を使用して、条件が相互に排他的になるようにします。

>>> x = 1
>>> y = 1
>>> z = 1
>>> if x == y and y == z: print("all the same")
elif not x == y and not y == z: print("all different")
else: print("neither")

all the same
>>> 
于 2013-09-19T20:04:37.147 に答える
0

私の提案は次のとおりです: 1) 入力を使用する 2) if、elif、else 句を使用する

このようなもの?

x = input("Enter the 1st integer")
y = input("Enter the 2nd integer")
z = input("Enter the 3rd integer")

if x == y and y == z:
    print("All the numbers are the same")

elif x!= y and y != z: # or use elif not and replace all != with ==
    print("None of the numbers are the same")

else:
    print("Neither")
于 2014-02-13T12:28:50.200 に答える