【发布时间】:2014-06-09 08:44:29
【问题描述】:
这是我在“尝试”中从用户输入的数字中查找最大 2 个值的代码:
#include <iostream>
using namespace std;
void maximum2(int a, int& max1,int& max2 ){
int temp = 0;
max2= a%10;
max1 = ((a/10)%10);
if (max2>max1) {
temp = max1;
max1 = max2;
max2 = temp;}
for(; a>0; a/=10){
if (a%10>max1)max1= a%10;
else if (a%10<max1 && a%10>max2) max2 = a%10;
}
}
void main(){
int max1, max2, num;
cin>>num;
maximum2(num,max1,max2);
cout<<"max 1 = "<<max1<<" max 2 = "<<max2<<endl<<endl;
}
它适用于大多数数字,例如例如34256 某些情况除外。例如,当我输入 54321 时,它给出的 max1 为 5,这是正确的,但它给出的 max2 为 1,这不是所需的值。你能帮我追踪我的错误吗?
【问题讨论】:
-
main必须返回int。 -
还是没有解决问题。
-
请重新缩进您的代码。此外,使用更多空间将增加代码的可读性,而不是像那样难以阅读的一堆东西。并且注意,在同一个循环中不需要多次计算
a % 10,这只是浪费运行时间 -
@user657267 在嵌入式系统中,main 不需要返回任何内容。旧的 C 编译器和 Visual C 都接受
void main(),无需关心 -
@LưuVĩnhPhúc 编译器足够聪明,可以使用临时值而不是一遍又一遍地计算相同的操作,如果它认为合适的话。
标签: c++ loops for-loop integer max