开发者

garbage value is obtained

开发者 https://www.devze.com 2023-02-22 03:35 出处:网络
this is a sample of my code. i am getting the value for maximum height. but my minimum height is a garbage value. what am i doing wrong

this is a sample of my code. i am getting the value for maximum height. but my minimum height is a garbage value. what am i doing wrong

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;

#define MAX 20

开发者_如何学Cstruct 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;
    }
}


Garbage in, garbage out. It looks like your input routine (which you didn't post) may be populating the data incorrectly. I'd look at the input data in the debugger (even if your choice of debugger is printf()).


Your code assumes that minimum is unequal to the maximum. Solution second if should be on its own and not in else clause from first.


assuming you do initialize the array in your real code, with these modifications:

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

this should be OK

0

精彩评论

暂无评论...
验证码 换一张
取 消