C ++如何调用if语句循环?

时间:2018-06-08 23:23:18

标签: c++

C ++代码,其中用户输入2个整数,然后程序输出这些整数之间的数量是3的倍数,包括两个数字,以及可以被5整除的数量。

这是我的代码。我想我没有正确地调用if语句。也许我需要一个开关?

#include <iostream>
#include <cmath>

using namespace std;

int main() {
    int numb1, numb2;
    int sentinel;
    int counter = 0;
    int mult3 = 0;
    int mult5 = 0;
    cout << "Enter an integer:";
    cin >> numb1;
    cout << "Enter another integer:";
    cin >> numb2;
    cout << endl;

    sentinel = (abs(numb2-numb1)+1);

    if(numb1 % 3 == 0 && counter <= sentinel) {
        mult3++;
        numb1++; 
        counter++;
    }
    else {
        numb1++; 
        counter++;
    }

    cout << endl;
    counter = 0;

    if(numb1 % 5 == 0 && counter <= sentinel) {
        mult5++;
        numb1++; 
    }
    else {
        numb1++;
        counter++;
    }
    cout << endl;

    cout << mult3 << " " << "numbers are divisible by 3 in between your entered integers." << endl;
    cout << mult5 << " " << "numbers are divisible by 5 in between your entered integers.";
    cout << endl;

    return 0;
}

3 个答案:

答案 0 :(得分:1)

下面给出了代码的简短版本。检查while循环(没有运行,只是从我的头顶开始)。

#include <iostream>
#include <cmath>

using namespace std;

int main() {
    int numb1, numb2;
    int sentinel;
    int counter = 0;
    int mult3 = 0;
    int mult5 = 0;
    cout << "Enter an integer:";
    cin >> numb1;
    cout << "Enter another integer:";
    cin >> numb2;
    cout << endl;

    while(numb1 <= numb2){
        mult3 += (numb1%3)==0?1:0; // (numb1%3)?0:1
        mult5 += (numb1%5)==0?1:0;
        ++counter;
        ++numb1;
    }
    cout << endl;

    cout << mult3 << " " << "numbers are divisible by 3 in between your entered integers." << endl;
    cout << mult5 << " " << "numbers are divisible by 5 in between your entered integers.";
    cout << endl;

    return 0;
}

答案 1 :(得分:0)

你根本没有循环它,所以这只会执行一次。

while(counter < sentinel)
{
  //run your tests and increment the appropriate variables if the numbers are divisible by 3 or 5
  counter++;
}

首先评估the lowest of the 2 entered numbers + counter % 3 == 0

答案 2 :(得分:0)

我明白了。我不得不使用3个单独的while循环。一个用于&lt;一个用于&gt;,一个用于=。当我只有一个&lt; =和&gt; =时,第一个循环将进入第二个循环。由于Avezan的帮助,我取出了哨兵和柜台。谢谢大家。