【问题标题】:Convert number to comma separated number将数字转换为逗号分隔的数字
【发布时间】:2014-08-14 15:02:13
【问题描述】:

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

#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

【问题讨论】:

  • 首先,花一些时间来格式化你的问题(如果有,因为我没有看到)
  • 向我们展示你的尝试,不要只是复制粘贴你的作业!
  • ...你的问题是...?
  • 嘘!您再次删除了所有代码格式!此外,this 已被多次询问 SO 本身!
  • printf("%06d", number);

标签: c


【解决方案1】:
#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);
}

【讨论】:

    【解决方案2】:
    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 2012-01-17
      • 2017-06-04
      • 2020-10-30
      • 2021-12-18
      相关资源
      最近更新 更多