【发布时间】:2019-05-25 21:56:18
【问题描述】:
我正在用 C++ 编写一个程序,其中输入是 N(村庄/行数)、M(天数/列数)和 H[N][M] 我单独输入温度的矩阵(最小 -50,最大 50)。
输出应该是最低村庄的总天数 temperature 具有最高的预测温度,然后是这些天的数量(列)以升序排列。
所以如果我输入这样的内容:
3 5
10 15 12 10 10
11 11 11 11 20
12 16 16 16 20
输出应该是:
2 2 3
或输入:
3 3
1 2 3
1 2 3
1 2 3
输出:
2 1 2
我的方法是首先将每天的最低气温和最高预报气温存储到两个单独的数组中,然后 然后编写一个 for 循环,在其中我每天检查每个村庄是否同时包含给定日期的最小值和从那天起的最高预测温度。
我有以下代码:
#include <iostream>
const int maxarr = 1000;
int H[maxarr][maxarr];
using namespace std;
void read(int N, int M, int t[maxarr][maxarr]);
void count(int N, int M, int t[maxarr][maxarr]);
int main()
{
int N;
int M;
cout<<"Number of villages? ";
cin>>N;
cout<<"Number of days? ";
cin>>M;
read(N,M,H);
count(N,M,H);
return 0;
}
void read(int N, int M, int t[maxarr][maxarr])
{
for(int i = 0; i < N ; i++)
{
for(int j = 0; j < M ; j++)
{
cin>>t[i][j];
}
}
}
void count(int N, int M, int t[maxarr][maxarr])
{
int mintemparr[maxarr];
int maxtemparr[maxarr];
int mintemp;
int maxtemp;
int days[maxarr];
int cnt = 0;
for(int j = 0; j<M; j++)
{
mintemp = 51;
for(int i = 0; i<N; i++)
{
if(t[i][j]<mintemp)
{
mintemp = t[i][j];
}
mintemparr[j] = mintemp;
}
}
for(int i = 0; i < M-1; i++)
{
maxtemp = -51;
for(int j = 0; j < N; j++)
{
for(int k = i+1; k < M; k++)
{
if(t[j][k]>maxtemp)
{
maxtemp = t[j][k];
}
}
maxtemparr[i] = maxtemp;
}
}
for(int i = 0; i < M-1; i++)
{
for(int j = 0; j < N; j++)
{
for(int k = i+1; k < M; k++)
{
if(t[j][i] == mintemparr[i])
{
if(t[j][k] == maxtemparr[i])
{
days[cnt] = i+1;
cnt++;
//tried an i++ here, didn't work as intended
}
}
else
{
j++;
}
}
}
}
cout<<cnt<<" ";
for(int i = 0; i < cnt; i++)
{
cout<<days[i]<<" ";
}
}
在某些情况下它可以完美运行,例如第一个输入时它的输出就是它应该的样子。但随着 我得到的第二个输入
6 1 1 1 2 2 2
和更长的 (1000x1000) 输入,我显然不能在这里复制也给出了错误的结果。 我怎样才能使这段代码按预期工作?
【问题讨论】:
-
您说“输出应该是温度最低的村庄预测温度最高的总天数”。我假设您在输入中提供的值是预测温度。但是你从哪里得到实际温度呢?你能解释一下你是如何根据提供的输入得到输出
2 2 3的吗? -
好的,所以第一天(列)包含温度 10、11 和 12。最低温度是 10。然后我检查最高预测温度。这一天的预报温度是这一天之后的所有温度。基于此,第 1 天的最高预测温度为 20。现在我检查 10 和 20 是否在同一行(村庄)。他们显然不是。然后我从第 2 天开始再次检查,依此类推。输出的第一个数字是发生这种情况的总天数,其他数字是这些天数(它们所在的列)。
-
感谢您的澄清。但是第二个输入不应该产生
3 1 2 3,因为所有3个村庄总是达到当天的最高预测温度和最低温度,因此所有三天都满足条件? -
完全有可能,抱歉。我也有我提到的更长的输入,也许你也可以快速看一下? www33.zippyshare.com/v/avNI69V4/file.html 这是一个我没有考虑和编写的示例输入。最后一天在这里如何输出有效?