如果否则错误:如何使其打印任何数字

If else error : How to make it print with any number?

本文关键字:何使其 打印 任何 数字 错误 如果      更新时间:2023-10-16

代码应将负数转换为 0。

负数有效,但正数不起作用

int main() {
   int userNum = 0;
   if (userNum >= 0)
      cout << "Non-negative" << endl;
   else
      cout << "Negative; converting to 0" << endl;
   userNum = 0;
   cout << "Final: " << userNum << endl; 
   return 0;
}

用户使用 99 时的预期输出

Non-negative 
Final: 99

打印Final消息之前,您将无条件地将userNum设置为 0,而不考虑其以前的值。 这是因为您的else块缺少一组大括号:

int main() {
   int userNum = 0;
   cout << "Enter a number: ";
   cin >> userNum;
   if (userNum >= 0)
      cout << "Non-negative" << endl;
   else
   { // <-- add this!
      cout << "Negative; converting to 0" << endl;
      userNum = 0;
   } // <-- add this!
   cout << "Final: " << userNum << endl; 
   return 0;
}