For循环不显示数组中最低的,而是第一个
For Loop Not displaying the lowest but the first in the array
伙计们,我是数组的新手,我正在编写一个程序,该程序需要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语句中也使用大括号。好的代码。
相关文章:
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 一个 2D 数组,并按行存储值.第一个循环用于行索引,第二个循环用于列索引
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- C++ 2D 数组在调用附近的小区时循环到行中的第一个单元
- 同一范围内矢量的两个独立"for"循环,仅打印第一个循环
- 如何在 for 循环中解决潜在的 getline() 问题,数组的第一个索引没有显示?
- 第一个循环用作无限循环
- 尝试使用while循环从文件中读取数据.还必须检查以确保第一个和唯一的值不是-1
- 为什么这个 while 循环不显示第一个元素?
- 尝试将文件读入结构数组,但 for 循环仅显示第一个索引,其余索引显示为零
- for 循环后的分号是什么意思?为什么第一个循环语句中有 j++
- 如何在 for 循环中取下第一个结果,使其不会重复
- 为什么第一个循环的剂量总是比第二个循环快
- 嵌套如果循环跳到第二个,即使第一个不为真
- 为什么在使用循环时忽略输入的第一个字符
- 第一个函数中的无限循环不知道如何解决
- 在C++标准中,当我同时使用 list.begin() 作为 list.splice() 的第一个和第三个参数时,为什么会发生无限循环
- 初学者:循环单链表的第一个程序
- C++ 只有第一个向量完成,push_back,cin,for 循环
- 如果在 for 循环的第一个循环中跳过语句