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

标签 c

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

#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

最佳答案

#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);
}

关于将数字转换为逗号分隔的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25311371/

相关文章:

c - 基本 C 编程_while_运行时错误

c# - 如何使用 FQL Facebook 获取评论评论

c - 如何形成数字数组,从 C 文件中获取输入

c - I2C 读取功能在发送确认位后卡住

c - Call-by-name 和 Call-by-macro-expansion 的区别

c - 如何对 char 数组的数组使用指针?

c - 部分提交黑客排名

c++ - openmp collapse with inner loop reduction

c - C 程序中位掩码的理解

检查矩阵中的行数是否等于 c 中的给定行数