For循环不显示数组中最低的,而是第一个

For Loop Not displaying the lowest but the first in the array

本文关键字:第一个 循环 显示 数组 For      更新时间:2023-10-16

伙计们,我是数组的新手,我正在编写一个程序,该程序需要2个并行数组找到最低和最高的值,然后根据值,它将获取与整数数组相关的最高字符串数组值,然后在屏幕上输出相关的最低和最高结果。

这是我目前所掌握的。

#include<iostream>
#include<string>
#include<climits>

//Prototypes:
using namespace std;
void getJars(string[], int[], int);
int getTotal(string[], int[], int);
int getLowest(string[], int[], int);

int main() {
    string salsa[] = { "Mild", "Medium", "Sweet", "Hot", "Zesty" };
    const int NUM = 5;
    int lowest = 0;
    int total = 0;
    int jars[NUM];
    getJars(salsa, jars, NUM);
    total = getTotal(salsa, jars, NUM);
    cout << endl << "Total of Jars Sold This Month: " << total << endl;
    lowest = getLowest(salsa, jars, NUM);
    cout << endl << lowest << endl;

    return 0;
}
void getJars(string salsa[], int jars[], int NUM) {

cout << "Salsa Sales Calculator...n";
cout << "------------------------n";
    for (int i = 0; i < NUM; i++) {
        cout << "Please Insert the Jar Amount for Each Salsa: ";
        cout << salsa[i];
        cout << " ";
        cin >> jars[i];
        cout << endl;
    }

    return;
}
int getTotal(string salsa[], int jars[], int NUM) {
    int total = 0;
    for (int i = 0; i < NUM; i++) {
        total += jars[i];
    }
    return total;
}
int getLowest(string salsa[], int jars[], int NUM) {
    int lowest = jars[0];
    string lowSalsa;
    for (int i = 0; i < NUM; i++) {
        if(lowest > jars[i])
            lowest = jars[i];

    return lowest;
}

我想看看为什么它只给我数组的第一个值,而不是最低的。谁能帮帮我。

for循环在第一次迭代时返回。

for (int i = 0; i < 5; i++) {
    if(lowest > jars[i])
        lowest = jars[i];

  return lowest;
}

切换"return"answers"}",它应该更正确地工作。为了清晰,我强烈建议在if语句中也使用大括号。好的代码。

相关文章: