【问题标题】:Skip every third number跳过每三个数字
【发布时间】:2018-03-07 20:54:46
【问题描述】:

我的任务是打印一组从 min 到 max 的数字(用户输入 min 和 mix),但每隔三个数字打印一个“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;

}

【问题讨论】:

  • int count = 0; 每次循环都会重新创建和重置count。将其移到 for 循环之外。

标签: c++ loops include counter iostream


【解决方案1】:

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

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;
}

【讨论】:

  • 终于!一个实际上解决了问题而不引入另一个实际上并没有避免需要执行 if 的运算符的人!
【解决方案2】:

模运算符% 返回除法运算的余数。 count++ 在每个循环中执行,因此语句 count % 3 为每个循环迭代返回 1、2、0、1、2、0 等。

当结果为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;
}

【讨论】:

  • 你可以用count代替(i - max + 1)
  • 不是(i - min + 1)?
  • @TonyDelroy - 你是对的。应该是这样:代替count,您可以使用(i - min + 1)
猜你喜欢
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 2014-08-31
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 2017-04-17
相关资源
最近更新 更多