将数字转换为逗号分隔数字

时间:2014-08-14 15:02:14

标签: c

我需要一种方法来打印long,其前导零以123,456形式,逗号在3 rd 和4 th 之间。我现在有这个代码:

#include <stdio.h>

void printWithComma (long num);

int main (void)
{ 
    long  number; 

    printf ("\nEnter a number with up to 6 digits: ");
    scanf ("%ld", &number);
    printWithComma (number);

    return 0;
} 


void printWithComma (long num) 
{ 
   //method to print the 6 digit number separated by comma
}

示例输出

运行1

Enter a number with up to 6 digits: 123456

The number you entered is       123,456

运行2

Enter a number with up to 6 digits: 12

The number you entered is       000,012

2 个答案:

答案 0 :(得分:0)

#include <stdio.h>

void printWithComma (long num);
int main()
{
    long number;

    printf("\nEnter a number with up to 6 digits: ");
    scanf ("%ld", &number);
    printWithComma(number);

    return 0;
}
void printWithComma (long num)
{
    int i, divisor, x;
    char s[8];
    divisor  = 100000;
    for(i = 0; i < 7; i++ ){
        if( i == 3){
            s[i] = ',';
            continue;
        }
        if(divisor == 1){
            s[i] =  num % 10 +  '0';
            break;
        }
        x = num / divisor;
        num %= divisor;
        s[i] = x + '0';
        divisor = divisor / 10;
    }
    s[7] = '\0';
    printf("\n%s\n", s);
}

答案 1 :(得分:0)

void printWithComma (long num) {
    //method to print the 6 digit number separated by comma
    char n[] = "000,000";
    char *p[6] = { n+6, n+5, n+4, n+2, n+1, n };
    int i;
    for(i=0;num && i<6;++i, num/=10){
        *p[i] += num % 10;
    }
    printf("\nThe number you entered is       %s\n", n);
}