【问题标题】:Producing Answer in Columns with different "for" loops在具有不同“for”循环的列中生成答案
【发布时间】:2018-03-11 01:05:05
【问题描述】:

我的任务是打印 3 列中的偶数、奇数和所有数字的列表。我设法让偶数列和奇数列工作,但不是 ALL 列工作。我知道这是因为 ALL 列在不同的 for 循环中,但我不确定如何解决这个问题,因为它需要在不同的“for”循环中才能按 1 计数,而不是像奇数和偶数一样按 2 . Click for Sample Output.

#include <iostream>
#include <iomanip>
using namespace std;
void no_10_add_even_odd_all_from_min_to_max(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_10_add_even_odd_all_from_min_to_max(min,max);
    return 0;
}

void no_10_add_even_odd_all_from_min_to_max(int min, int max){
    cout<<"10. Add the even , the odd, and ALL numbers";
    cout<<endl;
    const int SPACING =5;

    for(int n = min; n <= max; n+=2)
        cout<<setw(SPACING)<<n
            <<setw(SPACING)<<n+1<<endl;
    for(int n = min; n<=max; n++)
        cout<<setw(SPACING)<<n<<endl;
}

【问题讨论】:

  • 建议添加您获得的输出样本和您想要获得的输出,以消除回答者的歧义。

标签: c++ loops for-loop multiple-columns


【解决方案1】:

您可能需要将偶数和奇数转换为字符串,这样当您将它们全部打印出来但仍有所有数字要打印时,您可以什么都不打印:

void no_10_add_even_odd_all_from_min_to_max(int min, int max)
{
    cout << "10. Add the even, the odd, and ALL numbers" << endl;
    const int SPACING = 10;

    int even = min, odd = min;
    if (min % 2 == 0)
        ++odd;
    else
        ++even;

    for (int all = min; all <= max; ++all, even += 2, odd += 2) cout
        << setw(SPACING) << (even <= max ? to_string(even) : "") 
        << setw(SPACING) << (odd <= max ? to_string(odd) : "")
        << setw(SPACING) << all 
        << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2021-04-17
    • 1970-01-01
    • 2016-08-06
    相关资源
    最近更新 更多