跳过每三个数字

Skip every third number

我的任务是打印一组从最小到最大的数字(用户输入最小和混合),但每隔三个数字打印一个 "x"。我不确定如何设置它。我的朋友建议使用 count++,但我无法让它正常工作。它运行但不显示任何 X。

#include <iostream>
#include <iomanip>
using namespace std;
void no_5_count_from_min_to_max_skip_two(int min, int max);
int main()
{

    int min;
    int max;
    int first;
    int second; 

    cout<<"Enter first number:";
    cin>>first;
    cout<<endl;
    cout<<"Enter second number:";
    cin>>second;
    cout<<endl;

    if (first>second){
        max = first;
        min = second;
    }
    else{
        max = second;
        min = first;
    }

    no_5_count_from_min_to_max_skip_two(min,max);

    return 0;
}

void no_5_count_from_min_to_max_skip_two(int min, int max){
    cout<<"5.Counting from min to max but skip two:";
    cout<<endl;

    for(int i=min; i<=max; i++){
        int count = 0;
        count++;
        if (count==3){
            cout<<setw(4)<<"X";
            count = 0;
        }
        cout<<setw(4)<<i;
    }
cout<<endl;

}

您需要在循环之前创建 count,因为在您的代码中,您每次迭代都会创建一个新的循环,并打印 X 而不是 i 不在一起:

int count = 0;
for(int i=min; i<=max; i++){
    if (++count==3){
        cout<<setw(4)<<"X";
        count = 0;
    } else // print i only when X is not printed
        cout<<setw(4)<<i;
}

取模运算符 % returns 除法运算的余数。 count++ 在每个循环中执行,因此语句 count % 3 returns 1, 2, 0, 1, 2, 0, etc. for each loop iteration.

当结果为 0 时,您就知道是时候打印 'X' 了。如果不是,则打印 i.

记得在 1 开始 count,这样您就不会在第一次迭代时打印 'X'

void no_5_count_from_min_to_max_skip_two(int min, int max)
{
    cout << "5.Counting from min to max but skip two:";
    cout << endl;

    for (int i = min, count = 1; i <= max; i++, count++)
    {
        if ((count % 3) == 0)
            cout << setw(4) << "X";
        else
            cout << setw(4) << i;
    }
    cout << endl;
}