问题描述
int fizzbuzz1(int n)
{
if(n % 3 == 0 && n % 5 == 0)
{
printf("Fizzbuzz");
}
else if ( n % 5 == 0 && n % 3 != 0)
{
printf("Buzz");
}
else if (n % 5 != 0 && n % 3 == 0)
{
printf("Fizz");
}
else{
//I want to print the string representation of n here so for n = 2 I want
// "2" and not just 2
}
}
所以我从 python 知道你可以用 return str((n)) 返回一个整数作为字符串,但我如何在 C 中做到这一点?有人可以帮忙吗?
解决方法
根据您的函数原型,您似乎希望输出 n,而不是将其转换为字符串并返回。所以:
else{
printf("%d",n);
}
见printf format string。 printf
不仅可以打印精确的字符串,还可以打印各种形式的数字。在这里,您用 %d
表示希望这样做,然后提供数字作为第二个参数。 Here's a printf tutorial 我的搜索引擎排名很高;你可能会从中得到更多细节。
按字面意思回答这个问题:C 中没有可以直接传递的字符串类型;您最多可以返回一个指向 const char *
的指针。
但是如果你要返回一个指向某物的指针,你最好确保它指向的内存在函数的生命周期之后存在。 strdup
等标准函数返回 char *
并要求调用者负责稍后free
处理返回的内存。
还有像 snprintf
这样的函数要求调用者提供字符串的目的地,从而明显地表明它们负责内存管理。
你的函数有点奇怪,因为它可能返回一个字符串,或者它可能什么都不返回,只返回 printf
本身。在这种情况下,strdup
方法可能更有用,例如:
const char *fizzbuzz1(int n)
{
if(any of the other things) {
printf("Whatever");
return NULL;
}
else
{
// This'll definitely be big enough.
const size_t size = 1 + (3 * sizeof(n) * CHAR_BIT + 7) / 8;
char *result = malloc(size);
snprintf(result,size,"%d",n);
return result;
}
}
参见snprintf。现在调用者有额外的责任:
const char *fizzbuzzresult = fizzbuzz1(n);
if(fizzbuzzresult) {
/* do whatever */
free(fizzbuzzresult);
}