如何在C ++中每行打印3个不同的值

时间:2017-11-29 20:01:17

标签: c++ arrays fstream

我的程序从文件中读取366行数据,每行有2个值;最低温度和最高温度。我想在连续三天温度超过某个数字n时输出,用户输入。 这就是我所拥有的:

cout<<"Please enter a number to search: ";
cin>>n;
out<<endl;
out<<"Occasions during the year when there were three consecutive days 
where the temperature went above "<<n<<" are:"<<endl;
out<<"Days: ";
for(int x=0; x<366; x=x+1){
            in>>minimum[x];
            in>>maximum[x];


             if(minimum[x]>n){
              day1=x;
            }

             if(maximum[x]>n){
                day1=x;
            }
            out<<"Days: "<<day1<<", "<<day2<<", "<<day3<<endl;
            }

}

我无法理解如何将第2天和第3天更新为满足条件的数组的其他元素。满足条件时,我想存储日期并打印出来,如:

当温度超过34的连续三天时,一年中的情况(如果有的话)是:

天数:103,104,105

天数:107,108,109

天:288,289,290

天数是数组中的位置。

3 个答案:

答案 0 :(得分:1)

我建议你把它分解成更小的部分。例如,您可以通过两个主要步骤执行此操作:

  1. 读入所有数据
  2. 查找超过给定温度的所有3天
  3. 通过分别完成这些操作,您可以一次专注于一件,而不是尝试两者兼顾。

    请注意,您只需要if(maximum[x] > n)

答案 1 :(得分:1)

尝试更像这样的事情:

cout << "Please enter a number to search: ";
cin >> n;

out << endl;
out << "Occasions during the year when there were three consecutive days where the temperature went above " << n << " are:" << endl;

int firstday, numdays = 0;

for (int x = 0; x < 366; ++x)
{
    in >> minimum[x];
    in >> maximum[x];

    if (maximum[x] > n)
    {
        ++numdays;

        if (numdays == 1)
            firstday = x;
        else if (numdays == 3)
        {
            out << "Days: " << firstday << ", " << firstday+1 << ", " << firstday+2 << endl;
            numdays = 0;
        }
    }
    else
        numdays = 0;
}

可替换地:

cout << "Please enter a number to search: ";
cin >> n;

out << endl;
out << "Occasions during the year when there were three consecutive days where the temperature went above " << n << " are:" << endl;

for (int x = 0; x < 366; ++x)
{
    in >> minimum[x];
    in >> maximum[x];
}

for (int x = 0; x < 366-2; ++x)
{
    if (maximum[x] > n)
    {
        int firstday = x;
        int numdays = 1;

        for (int y = 1; y < 3; ++y)
        {
            if (maximum[x+y] > n)
                ++numdays;
            else
                break;
        } 

        if (numdays == 3)
            out << "Days: " << firstday << ", " << firstday+1 << ", " << firstday+2 << endl;

        x += (numdays-1);
    }
}

答案 2 :(得分:0)

创建一个int变量作为标志。每当你获得“好”的一天时,在该标志上加1,否则减去1。因此,最后,只需添加一个if语句来检查该标志变量是否为3,然后打印该值。

希望这有帮助!