简体   繁体   English

c: 我不明白的东西

[英]c: something i don't understand

I have this code :我有这个代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int i,j;
long int maxc=0,nn;

long int max(long int n)
{
    maxc=0;nn=n;i=1;

    if(n<10 && n>=0) 
        return n;

    while(nn!=0)
    {
        if(maxc<nn%10) 
        { 
            maxc=nn%10;
            j=i;
        }
        i++;
        nn/=10;
    }

    return maxc*(pow(10,i-2))+max(n/(pow(10,j))*(pow(10,j-1))+n%((int)pow(10,j-1)));
}

int main()
{
    long int n;
    printf("Dati n: ");
    scanf("%d",&n);
    printf("%ld",max(n));
    return 0;
}

n= numer given by user max=function that returns the maximum number consists of digits of n. n= 用户给出的数字 max=function 返回由 n 位数组成的最大数字。 EG: for n=1234.max should return 4321,for n=26341 ,max should return 64321例如:对于 n=1234.max 应该返回 4321,对于 n=26341,max 应该返回 64321

The problem is that sometimes works compiler,i mean for some number it returns the value I expect,but sometimes not.问题是有时编译器可以工作,我的意思是对于某些数字,它返回我期望的值,但有时不是。 usually return the same number of digits ,but replace (a) digit/s with 9 or 4... I can't get a rule to fix this problem.通常返回相同数量的数字,但用 9 或 4 替换 (a) digit/s ... 我无法找到解决此问题的规则。

Thank you !谢谢 ! I used codeblocks for ubuntu.我为 ubuntu 使用了代码块。

Stay away from pow .远离pow It is a floating-point function that approximate the result.它是一个近似结果的浮点函数。 If it return a value slightly too small (say 2.9999 rather than 3.00000), your code will truncate it to the nearest lower value (2).如果它返回的值稍微太小(比如 2.9999 而不是 3.00000),您的代码会将其截断为最接近的较低值 (2)。

I would strongly suggest an integer or character solution.我强烈建议使用整数或字符解决方案。

I won't give you the entire solution, but i will give you the idea.我不会给你完整的解决方案,但我会给你想法。

  • Scan the digits from the keyboard and store them in a long int variable.从键盘扫描数字并将它们存储在一个 long int 变量中。
  • Covert the digits to characters in an array.将数字转换为数组中的字符。 (don't forget about ASCII code). (不要忘记 ASCII 码)。
  • Sort he array in descending order.按降序对数组进行排序。
  • Print the array taking care of the ASCII code ( in my example i stored values not chars that's why i can print them as %d ).打印处理 ASCII 代码的数组(在我的示例中,我存储的值不是字符,这就是我可以将它们打印为 %d 的原因)。

     /* Prototypes*/ int stringConverter( char const * a, long int val ); void decsort( int * const a, int digits); int main( void ) { char a[ SIZE ]; int digits; long int val; printf( "Enter the number: " ); scanf( "%ld", &val ); digits = stringConverter( a, val ); decsort( a, digits ); /* Printer */ for( i = SIZE - digits - 1; i < SIZE; i++){ printf( "%d", a[ i ] ); } return 0; } int stringConverter( char * const a, long int val ) { int i, int j = 0; for( i = ( SIZE - 1 ); i >= 0; i-- ){ *( a + i ) = ( val % 10 ); j++; val = val / 10; if( val < 10 ){ i--; *( a + i ) = val; j++; break; } } return j; } void decsort( char * const a, int digits ){ /* Any sort */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM