【发布时间】:2015-09-22 16:33:19
【问题描述】:
我的问题是:如何将 first_In_Line 和 last_In_Line 变量传递出 for 循环,以便我的 final 语句接收变量并正确显示?
我假设学生的名字不同。
// This program allows a user to define class size, between 1 and 25
// students, and give a list of names. It does not store a list
// of names, but does sort the names to determine alphabetically,
// which student will be first in line, and who will be last.
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Non-user defined variables
int num_Students = 0;
string first_In_Line = "",
last_In_Line = "",
previous_Name = "";
bool compare = true;
// User defined variable.
string next_name;
// Get number of students from user between 1 and 25
cout << "Please enter the number of students in class between 1 and 25: ";
cin >> num_Students;
// Validate user input
while (num_Students < 1 || num_Students > 25)
{
cout << "Please enter a number between 1 and 25.";
cin >> num_Students;
}
for (int i = 1; i <= num_Students; i++)
{
cout << "What is the name of student " << i << "? ";
cin >> next_name;
if (compare == true)
{
if (next_name < previous_Name)
{
first_In_Line = next_name;
last_In_Line = previous_Name;
}
else if (next_name > previous_Name)
{
first_In_Line = previous_Name;
last_In_Line = next_name;
}
}
// Set compare to "true" to execute if statements next
// iteration of for-loop
compare = true;
previous_Name = next_name;
}
cout << first_In_Line << " is first in line." << endl;
cout << "And " << last_In_Line << " is last in line." << endl;
return 0;
}
输出是这样的,名称不正确:
请输入 1 到 25 之间班级的学生人数:3 学生1的名字是什么?亚当 学生2叫什么名字?马特 学生3叫什么名字?泽 马特排在第一位。 zed排在最后。
【问题讨论】:
-
呃,你提到了一个问题......它是什么?
-
好点...将编辑
-
您的变量是在 for 循环之外声明的,它们在循环之后仍然存在,您不必“传递”它们。你是如何使用你的程序的? (但是,是的,您的逻辑是错误的:您永远不会将新名称与您的
first_In_Line和last_In_Line进行比较。) -
好的,我来改一下
-
我正在为教育目的而上课的课程中使用该程序。
标签: c++ variables for-loop logic string-comparison