【问题标题】:why the if statement did not print out the string? cpp为什么 if 语句没有打印出字符串? cpp
【发布时间】:2020-03-31 16:44:10
【问题描述】:

我想在字符串中打印偶数和奇数,而不是在二进制中打印 true false | 1 / 0; 为什么输出仍然打印布尔值?

int main() {
    printf("enter the two numbers\n");
    int a;
    int b;
    cin >> a >> b;

    string arr[9] = {"one","two","three","four","five","six","seven","eight","nine"}; 
    for (int i = a; i <= b; i++)
    {
        if(i <=9){
           cout << arr[i-1] << "\n";
        }else{
           cout << ( i%2 == 0)? "even" : "odd"; // print out 1/0 but did not print out the even and odd
           cout << "\n";
        }
    }

    return 0;
}

输出:

enter the two numbers
9 16
nine
1
0
1
0
1
0
1

【问题讨论】:

标签: c++ arrays string printing


【解决方案1】:

您缺少括号来括住表达式。三元的优先级低于&lt;&lt;

cout << (( i%2 == 0)? "even" : "odd");

【讨论】:

  • 另外,i%2 == 0 周围的括号也不需要。
  • @PeteBecker 没错,但是我们这些每次都要看墙上图表的人无论如何都会忍不住把它们放进去。
  • @stark --(我(明白(你在说什么))))。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-20
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多