2015-03-13 62 views
-4

當用戶按Y或Y時應該停止該程序,但是測試測試條件對代碼沒有影響,程序不斷詢問用戶下一個數字。爲什麼測試條件沒有影響

#include<iostream.h> 
#include<conio.h> 
#include<math.h> 

int prime(int); 

void main(void) 
{ 
    int n; 
    char ch='i'; 

mylabel: 
    cout << "\nEnter num: "; 
    cin >> n; 
    cout << prime(n); 
    cout << "\nPress N or n to exit : "; 
    if (getche() != ('N' || 'n')) { 
     goto mylabel; 
    } 
    cout << ",,,"; 
} 

int prime(int p) 
{ 
    int test = 1; 
    if((p>2 && p%2==0) || p==0 || p==1 || p<0) 
     return 0; 
    for (int i=3 ; i<=(int(sqrt(p)))+1 ;i+=2) 
    { 
     if(p%i==0) 
     test=0; 
     break; 
    } 
    return test; 
} 
+0

爲什麼downvote? – Illaz 2015-03-13 13:46:30

+3

因爲這是一個愚蠢的問題,未來不會幫助任何人。你在哪裏讀到'if(getche()!=('N'||'n'))'是合併條件的正確方法?當然不是你的C++書。 – 2015-03-13 13:47:49

+0

@LightnessRacesinOrbit什麼是正確的方法? – Illaz 2015-03-13 13:49:32

回答

1

的問題是,你正在服用馬虎英文字面翻譯它來創建破碎C++。

當你說:

the character is not 'N' or 'n' 

這一點,而司空見慣,是錯誤。出於同樣的原因,您的C++代碼是錯誤。您正在比較getche()'N' || 'n',該表達式將布爾型OR應用於兩個char s,總是導致true

你的意思是說任:

the character is neither 'N' nor 'n' 
the character is not 'N' and the character is not 'n' 

C++只有後者構建一個等價的,那就是:

if (getche() != 'N' && getche() != 'n') 

當然,你只想讀一個字符,因此:

const char c = getche(); 
if (c != 'N' && c != 'n') 
+0

仍然不能正常工作 – Illaz 2015-03-13 13:52:12

+2

@HashirOmer:我不知道你對我最近的反饋意見中的大量信息有何期待。 – 2015-03-13 13:53:38

+2

感謝您的反饋。按4付款選項。 – 2015-03-13 13:53:50

相關問題