📅  最后修改于: 2023-12-03 14:59:44.894000             🧑  作者: Mango
FizzBuzz is a famous coding interview question that tests a programmer's ability to write clean and efficient code. It requires the programmer to write a program that prints the numbers from 1 to 100, with some specific rules:
In this article, we will implement the FizzBuzz problem in C++.
Here's the C++ code for the FizzBuzz problem:
#include <iostream>
int main() {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
std::cout << "FizzBuzz" << std::endl;
} else if (i % 3 == 0) {
std::cout << "Fizz" << std::endl;
} else if (i % 5 == 0) {
std::cout << "Buzz" << std::endl;
} else {
std::cout << i << std::endl;
}
}
return 0;
}
Let's go through this code step-by-step:
main()
function starts with a for
loop that goes from 1 to 100. We use the loop variable i
to represent the current number being printed.%
(modulus) operator to check if i
is divisible by 3, 5, or both. If i
is divisible by both 3 and 5, we print "FizzBuzz". If i
is only divisible by 3, we print "Fizz". If i
is only divisible by 5, we print "Buzz". Otherwise, we print the number itself.The FizzBuzz problem is a simple but effective way to test a programmer's ability to write clean and efficient code. In this article, we implemented the FizzBuzz problem in C++ and explained the code step-by-step. I hope this was helpful to you!