查找十进制数中的最大数字

时间:2011-11-29 00:22:40

标签: c

我正在尝试制作一个C函数,它会要求用户输入一个数字(44634329)并将scanf数字,保存到变量,并逐个数字,并且找出最大的数字。

http://pastebin.com/tF7PVtvg - 这是我目前的项目

void extractLargestDigit() {

int i;
i = 0;
int v;
v = 0;
int x;
x = 0;

printf("Enter an integer : ");
scanf("%d", &x);

    i = x % 10;
x = x / 10 % 10;

if(i >= x) { i = i; x = x / 10 % 10;}
if(x >= i) { i = x; x = x / 10 % 10;}
if(x = 0)  { i = i;}

就在这里,我正在尝试使程序循环,以便它将继续循环直到x等于0.我希望这将使i成为最大值数字,并将显示它。我还必须显示最大数字出现的位置,如数字542356976,最右边6位于第1位数位置,9位于第3位数位置,我需要显示最大位数出现的位置数字并没有完全弄明白

printf("\nThe largest digit : %d\n", i);
    printf("\nIts position : );


    return;
 }

任何帮助或见解都会很棒

6 个答案:

答案 0 :(得分:5)

为什么输入必须被视为整数?您可以考虑将输入视为字符串。然后,每个数字都是ascii字符数组中的char,这样就很容易遍历数字。

通过查看ascii表,您会注意到ascii数字0-9的数值是按升序排列的,这意味着比较它们的最大值是非常容易的。

答案 1 :(得分:2)

所以你想使用一个循环。

do {
   // grab input, process...
} while( x != 0 );

也...

if(x = 0)

这是一个赋值,即当执行时x将始终等于零,并且永远不会输入if块。如果要检查相等性,请使用==

if(x == 0)

答案 2 :(得分:2)

我会以不同的方式做到这一点:

void extractLargestDigit() {

    printf("Enter an integer : ");
    scanf("%d", &x);
    int max  = -1; // so it will always be less than any first digit

        while (x >0){
            int digit = X %10; //grab last digit
            x = x / 10;        //throw last digit away
            if (max < digit)       //if this digit is grater than current max...
                max = digit;       //... update it!
    }

    return max;
}

这样,你依次循环遍历每个数字,最大的数字将在max变量中。

答案 3 :(得分:1)

你需要一个循环。像这样:

while (x != 0)
{
  // ...

  x /= 10;
}

在循环中,检查当前的最后一位数字(x % 10),并跟踪最大数字。

答案 4 :(得分:0)

你想要这样的东西:

while(x>0)
{
     i=x%10;
     x/=10;
     // here check to see if 'i' is the biggest so far
}

另外,不要使用带有单字母名称的变量。很容易忘记它们是什么。 (事实上​​,我无法在您的代码中告诉哪个变量应该跟踪到目前为止找到的最大数字。)

答案 5 :(得分:0)

您的代码有点难以阅读,因为它现在已经格式化了。试试这个(你的教授会感谢你)因为我认为它会帮助你更好地理解你必须做的事情。我已经给你提示你下一步可能需要做什么。

void extractLargestDigit() {
   int i = 0; /* You can declare and initialise at the same time, by the way */
   int v = 0;
   int x = 0;

   printf("Enter an integer : ");

您希望在此功能和结束功能之间继续执行所有操作,直到用户输入零。你需要一个循环结构; C提供了一些。阅读do...whileforwhile循环,您会发现符合您需求的内容。

   scanf("%d", &x);

   i = x % 10;
   x = x / 10 % 10;

   if(i >= x) { 
       i = i; 
       x = x / 10 % 10;
   }
   if(x >= i) {
       i = x; 
       x = x / 10 % 10;
   }
   if(x = 0) { /* Something's not right here */ 
       i = i;
   }
}
相关问题