用C Fizzbuzz程序 [英] Fizzbuzz program in C

查看:155
本文介绍了用C Fizzbuzz程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这真的是不是太大的问题fizzbuzz,因为它是一个C的问题。

Okay, this really isn't as much a fizzbuzz question as it is a C question.

我写了一些C简单code为为需要fizzbuzz打印输出。

I wrote some simple code in C for printing out fizzbuzz as is required.

#include <stdio.h>

int main(void)
{
    int n = 30;
    int i;
    for (i = 1; i<=n; i++)
        printf("%s\n", (i % 15) == 0 ? "fizzbuzz" : (i % 5) == 0 ? "buzz" : (i % 3) == 0 ? "fizz" : i);
}

现在,最后一个else语句显然不能,因为printf的被接受的字符串,而'我'是一个int工作。
我的问题是,是否有任何形式的投,我可以申请转换的'我'为一个字符串?

Now, the last else statement obviously doesn't work since printf is accepting a string whereas 'i' is an int. My question is, is there any sort of cast that I can apply to convert the 'i' into a string?

编辑:我要提,我真正问的是,如果这fizzbuzz测试可以使用单个print语句来完成。没有特别的原因,我希望它只是比对是否可以做到的。好奇心其他单打印语句

I should mention, what I'm really asking is if this fizzbuzz test can be done using a single print statement. No particular reason why I want it to be a single print statement only other than curiosity of as to whether it can be done.

EDIT2:问题回答了,这里是我的实现:

Question answered and here's my implementation:

#include <stdio.h>

int main(void)
{
    int i, n=30;        
    for (i = 1; i<=n; i++)
        printf((!(i%3) || !(i%5)) ? "%s\n" : "%d\n", !(i % 15) ? "fizzbuzz" : !(i % 5) ? "buzz" : !(i % 3) ? "fizz" : i);
}

HTTP://$c$cpad.org/DN7yBW99

推荐答案

您已经通过你试过把所有的逻辑的printf 通话。这将是最好先将其写出来的慢的方式,然后寻找方法来以后优化它。

You've cornered yourself by the way you've tried to put all the logic inside of the printf call. It would be better to write it out the "slow" way first, then look for ways to optimize it afterward.

for (i = 1; i <= n; i++) {
    if (i % 15 == 0)
        printf("fizzbuzz\n");
    else if (i % 5 == 0)
        printf("buzz\n");
    else if (i % 3 == 0)
        printf("fizz\n");
    else
        printf("%d\n", i);
}

附录:只用一个printf的...

做吧

/* The following code is NOT recommended... */

int isFizz     = (i % 3 == 0      ) ? 1 : 0;
int isBuzz     = (i % 5 == 0      ) ? 1 : 0;
int isFizzBuzz = (isFizz && isBuzz) ? 1 : 0;

printf(
    (isFizz || isBuzz) ? "%s\n" : "%d\n",
    (
        isFizzBuzz ? "fizzbuzz" :
        isFizz     ? "fizz"     :
        isBuzz     ? "buzz"     :
        i
    )
);

HTTP://$c$cpad.org/LMr5WdIm

这篇关于用C Fizzbuzz程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆