这里的第一次海报。 请记住,我对c ++和编码一般都很新。 我正在尝试重写一个程序,询问用户他们想要比较多少个数字,然后输入每个数字的值。我通过for和if语句实现了这一点,但我现在被要求用用户定义的函数来做这件事。到目前为止我遇到的问题是我输入的第一个数字是保存的数字,但它会提示输入其他数字,并且函数内部的for循环正常工作。对我未正确做的一些建议将不胜感激。我已经声明了所有需要的变量,因此我只将原型放入以节省空间。
int main()
{
int DisplayGreatest(int,int);
do {
cout << "Please select an option" << endl;// Menu Options
cout << "A: Highest" << endl;
cout << "B:Lowest" << endl;
cout << "C: Quit " << endl;
cin >> Selection; // Menu Selection
cout << endl;
if ( (Selection == 'a') || (Selection == 'A') )
{
cout << "How many numbers do you want to use?" << endl;
cin >> Aselection;
cout << "enter your first choice" <<endl;
cin >> currentAinput;
DisplayGreatest (Aselection,currentAinput);
cout << "The largest number is "<< currentAinput << endl;
}
}
}
功能:
int DisplayGreatest(int Aselection, int currentAinput)
{
int i;
int keepAinput=0;
for(i=1;i<Aselection;i++)
{
cin >> currentAinput;
if (currentAinput > keepAinput)
{
keepAinput=currentAinput;
}
}
return currentAinput;
}
答案 0 :(得分:1)
您的代码中有几处错误:
这是一个功能版本:
#include <iostream>
using namespace std;
int DisplayGreatest(int Aselection)
{
int keepAinput = 0;
int currentAinput;
do {
cin >> currentAinput;
if (currentAinput > keepAinput)
{
keepAinput = currentAinput;
}
} while(--Aselection > 0);
return keepAinput;
}
int main()
{
char Selection;
do {
int Aselection;
int currentAinput;
cout << "Please select an option" << endl;// Menu Options
cout << "A: Highest" << endl;
cout << "B:Lowest" << endl;
cout << "C: Quit " << endl;
cin >> Selection; // Menu Selection
cout << endl;
if ( (Selection == 'a') || (Selection == 'A') )
{
cout << "How many numbers do you want to use?" << endl;
cin >> Aselection;
cout << "enter your first choice" <<endl;
cout << "The largest number is "<< DisplayGreatest (Aselection) << endl;
}
} while(Selection != 'C' && Selection != 'c');
}
答案 1 :(得分:0)
int DisplayGreatest(int,int)
可能应该在全局命名空间中声明,即:
int DisplayGreatest(int, int);
int main()
{
}
int DisplayGreatest (int Aselection, int currentAinput)
{
}
此外,你可以在一个循环中接受输入但是更自然地需要整个vector值的整数,然后使用相同的想法找到最高/最低(循环每个并保存当前最高/最低)。
编辑:哦,我现在看到你的问题了。您需要在函数末尾返回keepAinput,并将其分配给currentAinput或其他变量,并打印分配给它的任何一个。或者直接打印结果,IE:cout << "Highest number is " << DisplayGreatest(Aselection, currentAinput) << endl;