这是我的代码示例。我得到了最大高度的价值。但我的最小身高是垃圾值。我做错了什么
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
#define MAX 20
struct DATA
{
int id;
string name;
float height;
}numarray[MAX];
int main()
{
int num = 0;
numarray[num].height = fstr3;// contains float values from a file
float minimum, maximum;
minimum = numarray[0].height;
maximum = numarray[0].height;
for(int i = 0; i < MAX; i++)
{
{
if(numarray[i].height < minimum)
{
minimum = numarray[i].height;
}
else if(numarray[i].height > maximum)
{
maximum = numarray[i].height;
}
}
cout<< minimum<< " " << maximum<< endl;
return 0;
}
}
答案 0 :(得分:1)
垃圾进,垃圾出看起来您的输入例程(您没有发布)可能会错误地填充数据。我会查看调试器中的输入数据(即使您选择的调试器是printf()
)。
答案 1 :(得分:0)
您的代码假定最小值不等于最大值。 解决方案第二个if应该是自己的而不是来自first的else子句。
答案 2 :(得分:0)
假设您使用这些修改在实际代码中初始化数组:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
#define MAX 20
struct DATA
{
int id;
string name;
float height;
}numarray[MAX];
int main()
{
int num = 0;
numarray[num].height = fstr3;// contains float values from a file
float minimum, maximum;
minimum = numarray[0].height;
maximum = numarray[0].height;
for(int i = 1 /* skip 0 - already read */; i < MAX; i++)
{
if(numarray[i].height < minimum)
{
minimum = numarray[i].height;
}
// remove the else here
if(numarray[i].height > maximum)
{
maximum = numarray[i].height;
}
}
// move outside the loop
cout<< minimum<< " " << maximum<< endl;
return 0;
}
这应该没问题