C++ 如何根据输入的两种状态写入输出结果

C++ 如何根据输入的两种状态写入输出结果,c++,if-statement,C++,If Statement,我使用if命令决定两个输入A、B的输出,如表所示 A B write_output 0 0 1 1 >0 0 0 1 0 >0 1 0 >0 >0 0 0 例如,如果A>0且B=0,则我将输出值写入0和1。我正在使用if命令来实现它。但这不是我想要的桌子。你能帮我修一下吗 这是我的密码 std::ofstream myfile; myfile.open ("report.txt", std::ios::app); if(A=

我使用
if
命令决定两个输入
A、B
的输出,如表所示

 A   B   write_output
 0   0   1 1
>0   0   0 1
 0  >0   1 0
>0  >0   0 0
例如,如果A>0且B=0,则我将输出值写入0和1。我正在使用if命令来实现它。但这不是我想要的桌子。你能帮我修一下吗

这是我的密码

std::ofstream myfile;
myfile.open ("report.txt", std::ios::app);  
if(A==0 & B==0)
   myfile <<  1 << "\t" <<1<<'\n';
else if (A>0)
   myfile << 0 << "\t" <<1<<'\n';
else if (B>0)
   myfile << 1 << "\t" <<0<<'\n';
else
   myfile << 0 << "\t" <<0<<'\n';
myfile.close();

您可以看到第二列几乎是零值。这意味着如果(B>0),代码没有转到其他位置。

您的逻辑有缺陷。您需要在所有if分支中测试这两个条件。正如目前所写,你永远无法到达其他部分

应该是:

if(A==0 && B==0)
   myfile << 1 << "\t" << 1 << '\n';
else if (A>0 && B==0)
   myfile << 0 << "\t" << 1 << '\n';
else if (A==0 && B>0)
   myfile << 1 << "\t" << 0 << '\n';
else
   myfile << 0 << "\t" << 0 << '\n';
if(A==0&&B==0)

myfile如果(A==0&&B==0)需要使用
if(A==0&B==0)
而不是
if(A==0&B==0)
。使用
if(A==0&&B==0)
而不是
if(A==0&B==0)
&
在条件中使用的是按位的,您需要使用逻辑AND
&
。OP还需要在第二个if中完全测试
A>0&&B==0
条件,在第三个if中完全测试
B>0&&A==0
条件。
if(A==0 && B==0)
   myfile << 1 << "\t" << 1 << '\n';
else if (A>0 && B==0)
   myfile << 0 << "\t" << 1 << '\n';
else if (A==0 && B>0)
   myfile << 1 << "\t" << 0 << '\n';
else
   myfile << 0 << "\t" << 0 << '\n';