简体   繁体   中英

C++ Loop Through Array, Find Smallest

I'm trying to find the smallest value in 3 different array but it's not turning out right I don't think. It never seems to return the middle array even if it is the smallest. It's always either 0 or 2. What seems to be my logic error?

int smallest;
for(int i = 1; i < 3; i++)
{
    if(queue[i].getCount() < queue[0].getCount())
      smallest = i;
    else
      smallest = 0;
}

Given the errors in your code, it's a little difficult to see what you are trying to do.

I would think you want something more like this:

int smallest = queue[0].getCount();
for(int i = 1; i < 3; i++)
{
    if(queue[i].getCount() < smallest)
        smallest = queue[i].getCount();
}

If you instead want the resulting index, try something like this:

int smallest = 0;
for(int i = 1; i < 3; i++)
{
    if(queue[i].getCount() < queue[smallest].getCount())
        smallest = i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM