为什么测试条件没有效果
Why does the testing condition has no effect
当用户按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')
相关文章:
- unique_ptr:在分配之前调用 reset 有什么效果
- 如何使用 soong 命名空间来有条件地编译模块
- 有没有办法在 c++ 中拥有条件预处理器
- 提升::enable_if有两个条件
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 根据模板类型有条件地删除变量
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 有条件地选择带有 decltype() 和三元运算符的类型
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- C++ - 这个条件语句写得正确吗?还是有更有效的写法?
- 有条件的打印和计数在 std::map 上有限制
- 如何在 c++ 中有条件地包含标头?
- 如何仅在Qt是用ltcg构建时才有条件地启用ltcg?
- 如何在Visual Studio 2019中有条件地编译c++源文件
- C++可以有条件地向下转换类指针吗
- 在if条件下,右或左改变值的相等性检查是否有任何区别
- 使用 SFINAE 有条件地解析分配器成员
- 有条件地删除宏
- 有条件地包含C++标准库
- 尽管有停止条件,无限递归调用仍会执行,因为参数不会前进