2016-09-19 95 views
1

大概只是另一個noob問題,但我無法找到答案,所以... 我必須寫一個簡單的數字比較算法。我寫了這個程序,以便如果數字不相等,輸出將是一個比較,「最大的數字是x,最小的是y」;如果他們是平等的,程序會這樣說;並且,爲了安全起見,其他(如果由於任何原因而無法比較數字)輸出將是錯誤消息。從技術上講,這應該是一個非常簡單的任務,但是當我決定測試可能的結果時,以及可能導致錯誤的原因時,我發現當輸入都是字母時,輸出是相等的。當第一個輸入是數字,第二個輸入是字母時,它沒有輸出,它完全忽略了其餘的代碼。如果第一個輸入是一個字母,第二個輸入是一個比較,說明這個字母是最小的,值爲0.簡單比較promgram(對於數字)查看字母等於?

我只是一個初學者,所以如果任何人都可以向我解釋爲什麼這個發生或我怎麼能告訴程序只比較一個數值輸入...提前致謝!

下面的代碼(在Ruby中):

puts "\nEnter two positive numbers:\n\nFirst:" 
num1 = $stdin.gets.chomp.to_f 
puts "\nSecond:" 
num2 = $stdin.gets.chomp.to_f 

if num1 != num2 
    if num1 > num2 
     biggest = num1 
     smallest = num2 
    elsif num1 < num2 
     biggest = num2 
     smallest = num1 

    puts "\nThe biggest number is #{biggest} and the smallest is #{smallest}" 

    end 
elsif num1 == num2 
    puts "\nThe numbers are equal." 

else 
    puts "\nError" 
end 
+0

作爲一個說明:你有沒有輸出這個條件'如果NUM1> NUM2 ' – engineersmnky

回答

1

當你輸入的字母,然後出現這種情況:

"abc".to_f # => 0.0 

那麼,你是比較

0.0 == 0.0 

這顯然是真實的。

這是根據定義String#to_f以及String#to_i(只會返回0)的工作。

2

首先,解釋函數的行爲:

NUM1 = $ stdin.gets.chomp.to_f

這些線轉換進入到一個float什麼。當有人輸入一個整數時,你不會注意到,因爲它只是將(例如)1變成1.0。但是,字母轉換爲浮點數時返回0.0。所以上面引用的行將任何字母答案轉換爲0.0。

這就解釋了數字和字母之間的比較,並指出您只用正數測試;)

由於@engineersmnky在評論中指出,你有沒有輸出時NUM1> NUM2。將你的輸出移動到你的內部if/elseif塊之外。

那麼你對此做了什麼?

所有的輸入都是一個字符串,所以它會變得棘手。一種方法是,以除去.to_f和輸入傳遞到Integer()一個begin/catch block內,捕捉異常整數拋出如果輸入不能被轉換爲適當的整數:

puts "\nEnter two positive numbers:\n\nFirst:" 
num1 = $stdin.gets.chomp 
puts "\nSecond:" 
num2 = $stdin.gets.chomp 

begin 
    num1 = Integer(num1) 
    num2 = Integer(num2) 
rescue ArgumentError 
    { error handling code for improper input } 
end 

{ comparison code } 

如果用戶輸入一個字母, Integer()將會拋出一個ArgumentError,這段代碼將會捕獲並且你可以處理它,但是你喜歡(打印錯誤信息,提示用戶只輸入整數,退出等等)。)

2

除了其他的答案,我想指出以下...

if num1 != num2 
    if num1 > num2 
    biggest = num1 
    smallest = num2 
    elsif num1 < num2 
    biggest = num2 
    smallest = num1 
    puts "\nThe biggest number is #{biggest} and the smallest is #{smallest}" 
    end 

注意,puts只有在NUM1 < NUM2,所以它永遠不會出現在塊當NUM1> NUM2

爲了解決這個問題,只需移動end排隊

if num1 != num2 
    if num1 > num2 
    biggest = num1 
    smallest = num2 
    elsif num1 < num2 
    biggest = num2 
    smallest = num1 
    end 
    puts "\nThe biggest number is #{biggest} and the smallest is #{smallest}" 
end