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

How to print 3 different values per line in C++

我的程序从一个文件中读取了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

日期是数组中的位置。

创建一个 int 变量作为标志。每次你得到 'good' 天,就给那个标志加 1,否则减 1。所以,最后,只需添加一个 if 语句来检查该标志变量是否为三,然后打印该值。

希望对您有所帮助!

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

  1. 读入所有数据
  2. 找到高于给定温度的所有 3 天集合

通过分别执行这些操作,您可以一次专注于一件事情,而不是同时做两件事情。

请注意,您只需要 if(maximum[x] > 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;

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