Javascript中的FizzBu​​zz程序(详细说明) [英] FizzBuzz program (details given) in Javascript

查看:134
本文介绍了Javascript中的FizzBu​​zz程序(详细说明)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以为 FizzBu​​zz 更正我的此代码吗?似乎有一个小错误。下面的代码打印所有数字,而不是仅打印不能被3或5整除的数字。

Can someone please correct this code of mine for FizzBuzz? There seems to be a small mistake. This code below prints all the numbers instead of printing only numbers that are not divisible by 3 or 5.


编写打印数字的程序从 1 100 。但是对于三的倍数,打印Fizz而不是数字,并且对于五的倍数,打印Buzz。对于三和五的倍数的数字,打印FizzBu​​zz

Write a program that prints the numbers from 1 to 100. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".



function isDivisible(numa, num) {
  if (numa % num == 0) {
    return true;
  } else {
    return false;
  }
};

function by3(num) {
  if (isDivisible(num, 3)) {
    console.log("Fizz");
  } else {
    return false;
  }
};

function by5(num) {
  if (isDivisible(num, 5)) {
    console.log("Buzz");
  } else {
    return false;
  }
};

for (var a=1; a<=100; a++) {
  if (by3(a)) {
    by3(a);
    if (by5(a)) {
      by5(a);
      console.log("\n");
    } else {
      console.log("\n");
    }
  } else if (by5(a)) {
    by5(a);
    console.log("\n");
  } else {
    console.log(a+"\n")
  }
}


推荐答案

/*Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"*/

var str="",x,y,a;
for (a=1;a<=100;a++)
{
    x = a%3 ==0;
    y = a%5 ==0;
    if(x)
    {
        str+="fizz"
    }
    if (y)
    {
        str+="buzz"
    }
    if (!(x||y))
    {
        str+=a;
    }
    str+="\n"
}
console.log(str);

无论如何,您的函数都会返回虚假值,但无论如何都会打印。不需要让这个过于复杂。

Your functions return falsy values no matter what, but will print anyway. No need to make this overly complicated.

小提琴: http ://jsfiddle.net/ben336/7c9KN/

这篇关于Javascript中的FizzBu​​zz程序(详细说明)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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