我需要一种方法来打印带有前导零的 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/