[英]C++ two std::cout, only one outputting
我刚开始 C++ 编程。 完成 codecademy 课程后,我正在尝试一些项目。 我有一个程序接受 10 个人的输入,然后应该找出吃煎饼数量最多的人和吃最少的人。 我试过了:
我的代码:
主.cpp:
#include <iostream>
#include <string>
#include <vector>
#include "header.h"
std::vector<int> person = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<int> num_eaten_pancakes(10);
int most_pancakes = 0;
int least_pancakes = 0;
int person_who_ate_most = 0;
int person_who_ate_least = 0;
int main() {
get_nums_of_pancakes();
person_who_ate_most = who_ate_most();
std::cout << "Person " << who_ate_most() << " ate the most pancakes with " << num_eaten_pancakes[person_who_ate_most - 1] << " eaten." << std::flush;
person_who_ate_least = who_ate_least();
std::cout << "Person " << who_ate_least() << " ate the least pancakes with " << num_eaten_pancakes[person_who_ate_least - 1] << " eaten." << std::flush;
return 0;
}
函数.cpp
#include <iostream>
#include <string>
#include <vector>
#include "header.h"
void get_nums_of_pancakes() {
//Get the no. of pancakes eaten by person 1, 2, etc. up to person 10.
for (int i = 0; i < 10; i++) {
person[i] = i + 1;
std::cout << "Input the number of pancakes entered by person " << person[i] << ": ";
std::cin >> num_eaten_pancakes[i];
}
}
//Who ate the most pancakes
int who_ate_most() {
for (int i = 0; i < 10; i++) {
if (num_eaten_pancakes[i] > most_pancakes) {
most_pancakes = num_eaten_pancakes[i];
person_who_ate_most = person[i];
}
}
return person_who_ate_most;
}
//Who ate the least pancakes
int who_ate_least() {
for (int i = 0; i < 10; i++) {
do
least_pancakes = num_eaten_pancakes[i];
while (i == 0);
if (num_eaten_pancakes[i] < least_pancakes) {
least_pancakes = num_eaten_pancakes[i];
person_who_ate_least = person[i];
}
}
return person_who_ate_least;
}
header.h
#include <vector>
#include <string>
//VARIABLES
//Vectors for 10 people, pancakes
extern std::vector<int> person;
extern std::vector<int> num_eaten_pancakes;
extern int most_pancakes;
extern int least_pancakes;
extern int person_who_ate_most;
extern int person_who_ate_least;
//FUNCTIONS
void get_nums_of_pancakes();
int who_ate_most();
int who_ate_least();
output,当我输入消耗的煎饼数量时,对于吃得最多的人来说是正确的,但是对于吃得最少的人来说,什么都没有。
提前致谢!
在who_ate_least()
中有一个无限的 do-while-loop:如果i == 0
你永远不会改变i
并且永远不会使条件变为假。
你在这部分有无限循环,所以 function who_ate_least
卡住了。
do
least_pancakes = num_eaten_pancakes[i];
while (i == 0);
我认为您应该将“who_ate_least()”function 更改如下:
int who_ate_least() {
for (int i = 0; i < 10; i++) {
if(i==0)
least_pancakes = num_eaten_pancakes[i];
if (num_eaten_pancakes[i] <= least_pancakes) {
least_pancakes = num_eaten_pancakes[i];
person_who_ate_least = person[i];
}
}
return person_who_ate_least;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.