为什么答案不会显示

Why answers won't show

本文关键字:显示 答案 为什么      更新时间:2023-10-16

我正在学习 c++,说实话,我是新手,犯了基本错误。 我已经开始编写代码来显示键入的数字是否可以被 2、4、5、8、10 整除到 5 次

问题是它没有显示答案...

#include <iostream>
using namespace std;
int main() {
int num;
cout << "type in number to check if number is divisible by 2, 4, 5, 8, 10" << endl;
cin >> num;
switch (num) {
case 1:
if (num / 2 == 0) {
cout << num << "is divisble by 2" << endl;
}
case  2:
if (num / 4 == 0) {
cout << num << "is divisible by 4" << endl;
}
case  3:
if (num / 5 == 0) {
cout << num << "is divisible by 5" << endl;
}
case  4:
if (num / 8 == 0) {
cout << num << "is divisible by 8" << endl;
}
case  5:
if (num / 10 == 0) {
cout << num << "is divisible by 10" << endl;
}
num++;
if (num == 5) break;
}
return 0;
}

你对switch语句的理解是不对的。

switch(num) {
case 1 :
// This block will be executed only when num is equal to 1.
if (num/2 == 0)  {
cout<<num<<"is divisble by 2"<<endl;}

对于您的问题,您只需要一系列if语句。

cin >>num;
if (num % 2 == 0)  {  // Not  if ( num/2 == 0)
cout<<num<<"is divisble by 2"<<endl;
}
if (num % 4 == 0){
cout<<num<<"is divisible by 4"<<endl;
}
if (num % 5 == 0) {
cout<<num<<"is divisible by 5"<<endl;
}
if (num % 8 == 0){
cout<<num<<"is divisible by 8"<<endl;
} 
if (num % 10 == 0)
{
cout<<num<<"is divisible by 10"<<endl;
} 

您似乎认为将一个整数除以另一个整数会返回余数。事实并非如此。num等于6num / 2将返回3并且对于等于7num将返回相同的结果。

你想要的是取模运算符%它返回除法余的值。 所以,对于6 % 2你会得到0,对于7 % 2你会得到1

另请参阅:https://en.cppreference.com/w/cpp/language/operator_arithmetic

你不应该使用除法运算符来检查你是否得到任何余数。相反,您应该使用取模运算符来检查是否得到任何余数。 例如:

x = 10 % 4

会提醒您 2,因为 10 除以 4 的结果在 2

。您可以在 c++ 中的运算符中阅读有关运算符的更多信息。

您也可以在 switch 语句中添加一个检查,以检查 num == 是否为 0

switch(num != 0)

您可以对

switch(num != 0){
case 1:
if( (num % 2) == 0){
cout << num << " is divisible by 2" << endl;
}
case 2:
if( (num % 4)== 0){
cout << num << " is divisible by 4" << endl;
}
case 3:
if((num % 5) == 0){
cout << num << " is divisible by 5" << endl;
}
case 4:
if((num % 8) == 0){
cout << num << " is divisible by 8" << endl;
}
case 5:
if((num % 10 )== 0){
cout << num << " is divisible by 10" << endl;
}
num++;
if(num == 5)break;

希望对您有所帮助!