gpt4 book ai didi

c++ - bool 变量。检查的逻辑

转载 作者:行者123 更新时间:2023-11-30 02:01:40 29 4
gpt4 key购买 nike

所以我有一个关于 bool 变量的问题。

这是一个检查是否按时支付到期款项的程序,如果没有,则乘以 1.10。

#include <iostream>
using namespace std;
int main()
{
float Dues;
cout<<"Enter ammount: \n";
cin>>Dues;
cout<<"On time? (y/n)";
char yn;
cin>>yn;
bool Overdue = yn !="y"; //TRUE (1) if it is late, FALSE (0) if it is on time
float AmountDue;
AmountDue = Overdue ? Dues*1.10 : Dues;
cout<<"Ammount due: ";
cout<<<<AmountDue;
return 0;

}

我不理解 bool 的逻辑

我们有

bool Overdue = yn !="y";

现在这是我对 bool 逻辑的理解,它不对

如果输入“n”=> N 不是 Y,这是正确的,因此 bool 为真 => 1

如果输入“y”=> Y 不是 Y,这是错误的,因此 fasle => 0

但实际上恰恰相反,我无法从逻辑上向自己解释。bool Overdue = yn !="y"; 基于什么逻辑?

最佳答案

除了 jrok 的回答之外,您遇到的问题是您假设小写字符和大写字符是同一回事。他们不是。 'y' 和 'Y' 是两个不同的字符。 'n' 和 'N' 也一样。

你写:

If "n" is entered => N is NOT Y which is CORRECT therefore the bool is true => 1

没有。 'n' 不是 'y'。

If "y" is entered => Y is NOT Y which is WRONG, therefore fasle => 0

这是正确的。 “y”不是“Y”。

试试这个:

bool Overdue = (yn != 'n') && (yn != 'N');

关于c++ - bool 变量。检查的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13879624/

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