gpt4 book ai didi

c++ - 为什么切换 if else 语句的顺序会导致错误?

转载 作者:行者123 更新时间:2023-12-01 14:34:02 24 4
gpt4 key购买 nike

这是我的代码:

/* 
Given a positive integer denoting n, do the following:
- If 1 <= n <= 9, then print the lowercase English word corresponding to
the number (e.g., one for 1, two for 2, etc.)
- If n > 9, print 'Greater than 9'.
*/

#include <iostream>
#include <array>

using namespace std;

int main()
{
string english_names [9] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
int n;
cin >> n;
if(n>9) {
cout << "Greater than 9";
}
else {
cout << english_names[n-1];
}
}

使用上面的代码效果很好,但是如果我将 if else 语句更改为:

if(1<=n<=9) {
cout << english_names[n-1];
}
else {
cout << "Greater than 9";
}

然后程序就不能正常工作了。它适用于整数 n,其中 1 <= n <= 9,但是如果整数大于 9,程序将不起作用。

最佳答案

这个表达式:

if(1 <= n <= 9)

检查是否n介于 1 和 9 之间。检查实际上变为:

if( (1 <= n) <= 9)

这将是 0 <= 9 , 或 1 <= 9 , 两者都是 true .

你需要做的:

if(1 <= n && n <= 9)

关于c++ - 为什么切换 if else 语句的顺序会导致错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62220228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com