2015-03-13 61 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

相关问题