简体   繁体   English

C ++中的条件语句问题

[英]Conditional Statement issue in C++

Here is the question that I've been trying to solve: 这是我一直试图解决的问题:

You are given a positive integer, n,: 你得到一个正整数,n,:

If 1 ≤ n ≤ 9, then print the English representation of it. 如果1≤n≤9,则打印它的英文表示。 That is " one " for 1, " two " for 2, and so on. 这是1的“ ”,2的“ ”,依此类推。

Otherwise print " Greater than 9 " (without quotes) 否则打印“ 大于9 ”(不带引号)

Here is a portion of my suggested answer, but it doesn't work! 这是我建议的答案的一部分,但它不起作用!

int n;

if (1 <= n <= 9) {
    if (n == 1) {
    cout << "one" << endl;
    } else if (n == 2) {
    cout << "two" << endl;
    } else if (n == 3) {
    cout << "three" << endl;
    } else if (n == 4) {
    cout << "four" << endl;
    } else if (n == 5) {
    cout << "five" << endl;
    } else if (n == 6) {
    cout << "six" << endl;
    } else if (n == 7) {
    cout << "seven" << endl;
    } else if (n == 8) {
    cout << "eight" << endl;
    } else if (n == 9) {
    cout << "nine" << endl;
    }
} else {

    cout << "Greater than 9" << endl;
}

What is the issue with the code? 代码有什么问题?

if (1 <= n <= 9)更改为if (n>= 1 && n<=9)

if (1 <= n <= 9) doesn't do what you think it does. if (1 <= n <= 9)没有做到你认为它做的事情。 It's evaluated as ((1 <= n) <= 9). 它被评估为((1 <= n)<= 9)。 <= returns a Boolean, so you're checking if 'true' or 'false' is less than 9. <=返回一个布尔值,因此您要检查'true'或'false'是否小于9。

You want to use the 'and' operator, &&. 你想使用'和'运算符,&&。

if (1 <= n <= 9) { should be if (1 <= n && n <= 9) { if (1 <= n <= 9) { if (1 <= n && n <= 9) {

You could also arrive at the solution by using the switch statement: 您也可以使用switch语句到达解决方案:

//Problem states n is a positive integer, so no need to check if n < 1
switch(n)
{
  case 1: cout << "one" << endl; break;
  case 2: cout << "two" << endl; break;
  //etc...
  case 9: cout << "nine" << endl; break;
  default: cout << "Greater than 9" << endl;
}

It does the same thing, but it looks cleaner in my opinion. 它做了同样的事情,但在我看来它看起来更干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM