循环和模数

时间:2017-01-21 17:45:50

标签: c++

我不确定为什么此代码无法按预期工作。 “输入%7!= 3 ||输入%7!= 4)”。我是说输入模7不等于3或4然后保持循环。但是当我输入10时,当10模7等于3时,它仍然不起作用。

#include <iostream>
#include <string>

using namespace std;

int main(){
int input;
int count = 1;
cout << "Please Enter a positive integer that is 3 or 4 modulo 7: ";
cin >> input;

while (input <= 0 || input % 7 != 3  || input % 7 != 4){
count++;
cout << count << "tries, " << "please try again: ";
cin >> input; 
}

cout << "Congratulations, you passed";
 return 0;    
}

3 个答案:

答案 0 :(得分:1)

  

我说如果输入模7不等于3或4则保持循环。

在这种情况下,您需要将条件更改为:

while (input <= 0 || (input % 7 != 3  && input % 7 != 4))

答案 1 :(得分:1)

存在逻辑错误,此处,这是您可能需要的条件:

while (input <= 0 || (input % 7 != 3  && input % 7 != 4)){

你想留在循环中,而modulu与3和4都不同。

答案 2 :(得分:1)

  

我不确定为什么此代码无法按预期工作。 “输入%7!= 3 ||输入%7!= 4)”。我是说输入模7不等于3或4然后保持循环

不,你不是!

你是说输入modulo 7 不等于 3 ,或者输入modulo 7 不等于 4 ,留在循环中。

该条件始终成立,因为输入模7 不能同时 3 4

这种逻辑连接词的重写实际上是英语错误;虽然用英语口语接受,但它不是用C ++语言。

你的意思是“如果输入模7不等于3,输入模7不等于4,则保持循环”,即input % 7 != 3 && input % 7 != 4