C++ 两个std::cout,只有一个输出

C++ two std::cout, only one outputting

我刚刚开始学习 C++ 编程。完成代码学院课程后,我正在尝试一些项目。我有一个程序接受 10 个人的输入,然后计算出吃煎饼最多的人和吃最少的人。我试过:

我的代码:

main.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;
    }

funcs.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();

当我输入消耗的煎饼数量时,输出对于吃得最多的人是正确的,但对于吃得最少的人来说,则没有任何结果。

提前致谢!

你在 who_ate_least() 中有一个无限的 do-while 循环:如果 i == 0 你永远不会改变 i 并且永远不会使条件变为假。

你在这部分遇到了无限循环,所以函数 who_ate_least 卡住了。

     do
        least_pancakes = num_eaten_pancakes[i];
     while (i == 0);

我认为您应该按如下方式更改 "who_ate_least()" 函数:

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