开发者

Maximum of several numbers

Hey guys I just completed this:

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

This clearly only works for 6 entries. I want to make so if you enter 2, 3, 4, or 5 entries, it would still work! I'm guessing I have to add break, just not sure.


Tip: you don't actually need to store every character that is inserted.

You can simply have one variable to keep the actual "current maximum" and, every time the user inputs a new number, you compare the "current maximum" with the new number: if the current maximum is greater you simply discard the new input, if it's less, instead, the new input becomes the new maximum.

To allow the user to input how many characters he wants (until e.g. he inserts a "special" one to exit) you can use a while loop.


You should seriously read a introductory book on c++(or any programming language).

Anyway, here's how you might do this.

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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜