为什么测试条件没有效果

Why does the testing condition has no effect

本文关键字:有效果 条件 测试 为什么      更新时间:2023-10-16

当用户按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;
}

问题是你正在采用草率的英语并按字面翻译以创建破碎的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')