【发布时间】:2024-08-31 12:05:01
【问题描述】:
我刚刚开始 C++ 编程。完成 codecademy 课程后,我正在尝试一些项目。我有一个程序接受 10 人的输入,然后应该找出吃煎饼数量最多的人和吃最少的人。我试过了:
- std::endl;在每个 cout 结束时。
- 标准::刷新;最后。
- 这在我的机器上不起作用后,我将代码放入repl.it,它仍然不起作用。这(根据我对 repl.it 工作原理的理解)排除了编译器/ide(即 g++ 和 Visual Studio 2019)的问题。
我的代码:
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();
输出,当我输入消耗的煎饼数量时,对于吃得最多的人来说是正确的,但对于吃得最少的人来说,什么都没有。
提前致谢!
【问题讨论】:
-
您是否尝试过使用调试器逐句逐句执行代码以查看实际发生的情况?如果不是,那么现在正是这样做的最佳时机,并学习如何使用除了编译器本身之外最重要的工具之一。
-
do least_pancakes = num_eaten_pancakes[i]; while (i == 0);这不会很快结束。 -
"这不打印任何东西" != "我的程序永远不会结束"
-
@Someprogrammerdude 我不太确定如何使用调试器。目前我只是按下按钮并检查它是否有效,哈哈。不过,我真的很想学习如何正确使用它。你有学习如何使用它的资源吗?谢谢。