0” ___0”
10英寸__10英寸
999``_999''
1000“1000”
9999``9999''
10000或更多''****''
我需要知道如何在C语言中执行此操作。 一种可行的算法是除以10。有什么好主意吗?
答案 0 :(得分:1)
类似的东西?
#include <stdio.h>
#include <string.h>
void f(unsigned n)
{
if (n >= 10000)
puts("'**** '");
else {
char s[5];
int ln = sprintf(s, "%u", n);
printf("'%s%s '\n", "____" + ln, s);
}
}
int main()
{
f(0);
f(10);
f(999);
f(9999);
f(10000);
return 0;
}
执行:
'___0 '
'__10 '
'_999 '
'9999 '
'**** '
或者如果您想获取字符串而不是仅仅打印它:
#include <stdio.h>
#include <string.h>
/* place the result in 'r' and return it */
char * f(unsigned n, char * r)
{
if (n >= 10000)
strcpy(r, "**** ");
else {
char s[5];
int ln = sprintf(s, "%u", n);
sprintf(r, "%s%s ", "____" + ln, s);
}
return r;
}
int main()
{
unsigned v[] = { 0, 10, 999, 1000, 9999, 10000, 123456 };
char r[6];
for (size_t i = 0; i != sizeof(v) / sizeof(unsigned); ++i)
printf("\"%s\"\n", f(v[i], r));
return 0;
}
执行:
"___0 "
"__10 "
"_999 "
"1000 "
"9999 "
"**** "
"**** "