2011-09-18 36 views
0

嗨我刚刚完成这个的:最大的几个数字

#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个条目,它仍然可以工作!我猜我必须补充休息,只是不确定。

+1

遵守零一无穷规则并使用容器/循环使其适用于任何数字的情况如何? – PlasmaHH

+0

建议:为什么不使用'char [6]'而不是有6个不同的标识符? – Mahesh

+0

您是否考虑过使用数组来存储输入值,然后循环遍历数组? – entitledX

回答

5

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

您可以只保留一个变量来保持实际的“当前最大值”,并且每次用户输入一个新的数字时,都会将“当前最大值”与新数值进行比较:如果当前最大值超过了,新输入(如果它较少),而是新输入成为新的最大值。

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

+0

像这样..:while(!)(0)if号码= 10还是你的意思是不同的? – johnmath15

+0

为什么你把所有的模('%')和分区的东西?您只需在每次迭代中阅读用户输入,并检查它是否大于您当前的最大值... –

+0

是的,但我不确定如何! – johnmath15

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; 

} 
+0

嘿,那是伟大的..我想知道什么 - n的意思?? – johnmath15

+0

@ johnmath15它简写为:n = n - 1 – vivek

+0

为什么代码只与那个? – johnmath15