最多几个数字

时间:2011-09-18 21:11:02

标签: c++

嘿伙计们我刚刚完成了这个:

#include <iostream>

using namespace std;

int main()
{
    char a, b, c, d, e, f;
    char max;

    cout << "enter a b c: ";
    cin >> a >> b >> c >> d >> e >> f;

    max = a;
    if (b > max)
        max = b;
    if (c > max)
        max = c;
    if (d > max)
        max = d;
    if (e > max)
        max = e;
    if (f > max)
        max = f;

    cout << "max is " << max << "\n";

    return 0;
}

这显然仅适用于6个条目。我想这样做,如果你输入2,3,4或5个条目,它仍然可以工作!我猜我必须添加休息,但不确定。

2 个答案:

答案 0 :(得分:5)

提示:您实际上并不需要存储插入的每个字符。

您可以简单地使用一个变量来保持实际的“当前最大值”,并且每次用户输入新数字时,您将“当前最大值”与新数字进行比较:如果当前最大值更大,则只需丢弃新输入,如果它更少,则新输入成为新的最大值。

要允许用户输入他想要的字符数(例如,他插入“特殊”字符退出),您可以使用while循环。

答案 1 :(得分:1)

你应该认真阅读关于c ++(或任何编程语言)的入门书。

无论如何,你可以这样做。

#include <iostream>

using namespace std;

int main(){
char ch,max = 0;
int n=0;
cout<<"\nEnter number of characters :";
cin>>n;
cout<<"\nEnter characters\n";
while(n>0)
{
    cin>>ch;
    if(max<ch)
        max = ch;
    --n;
}

cout<<"Max : "<<max;


return 0;

}
相关问题