输入后,我的程序似乎跳过了第一个IF语句,直接转到ELSE

After input my program seems to skip the first IF statement and go directly to ELSE

本文关键字:语句 IF ELSE 第一个 过了 我的 程序 输入      更新时间:2023-10-16

我的代码有问题。它编译时没有错误,但在从用户那里获得输入后,即使有正确的值,它似乎也会跳过第一个条件语句,直接转到ELSE,从而导致程序终止。我似乎找不出这种行为的原因。

我认为这可能是条件语句构造方式的问题:if( ((S <= 25 && S <= 75) % 5 == 0) && (U < 0.2 && U < 0.7) ){

我需要检查输入的值是否是25 <= S <= 75,是否可以被5整除,以及另一个值是否为0.2 < U < 0.7

课程分配

//#include "stdafx.h" // Header File used VS.
#include <iostream>
//#include <iomanip> // Used to format the output.
#include <cstdlib> // Used for system().
#include <math.h> // Used for sqrt().
using namespace std;// ?

int main (){
int S; // Gram/Litre
double U; // Specific Max. Growth Rate. Per Hour.
double D; // Maximum Dilution Rate.
const int K = rand() % 7 + 2; // Saturation Constant - Randomly Gegerated Number Between 2 & 7. In Hour/Litre.
cout << "Enter value between 25 and 75, divisible by 5, for S in Gram/Litre: ";
cin >> S;
cout << "Enter value bigger than 0.2, but less than 0.7, for U per Hour: ";
cin >> U;
if( ((S <= 25 && S <= 75) % 5 == 0) && (U < 0.2 && U < 0.7) ){ // Check Condition ***May Need Adjustments***
D = U * ( 1 - sqrt ( K / ( K + S) ) ); // Might have to adjust values to fit data type double. Add .00
cout.precision(3); // Prints 3 values after decimal point.
cout << "Maximum dilution rate is: " << D << endl;
if( D < 0.35 && D < 0.45 ){
cout << "Kinetic parameters are acceptable." << endl;
}
else{
cout << "Kinetic  parameters are not acceptable." << endl;
}
}
else{
cout << "Invalid Input. Program will now terminate." << endl;
}
system("PAUSE"); // Pauses the program before termination.
return 0;
}

首先,如果您想要25<=S<=75,你应该25 <= S && S <= 75而不是S <= 25 && S <= 75。与U < 0.2D < 0.35相同——它们应该是0.2 < U0.35 < D

其次,上面的语句返回一个布尔值-因此,如果S是一个介于25和75之间的值,则布尔值将强制转换为1的整数值,并且1 % 5 == 0始终为false。(类似地,如果S在此范围之外,则布尔值将强制转换为整数0,并且0 % 5 == 0将始终为真)

正确、完整的if语句如下:

if((25 <= S && S <= 75) && (S % 5 == 0) && (0.2 < U && U < 0.7)){ ... if(0.35 < D && D < 0.45){ ... } ... }

如果从输入中读取25到75之间的数字,则if( ((S <= 25始终为false。

您必须使用if( ((S >= 25 && ...

问题主要在于循环条件。例如,代码中的这一行:

if( ((S <= 25 && S <= 75) % 5 == 0) && (U < 0.2 && U < 0.7) ){ 
//...
}

如果条件S<=25&amp;S<=75可以简单地重写为S<=25,因为换句话说,您的参数表示如果S小于或等于25,或者如果S小于等于75,依此类推

这里也存在同样的问题:U<0.2&amp;U<0.7。if语句再次简单地检查U是否小于0.2和U是否小于0.7,如果前者为真,则后者始终为真。

但是,在接受2个输入之前的输出语句中,您声明S的范围应为25<=S<=75,意味着S大于25;并非更少。对于U来说,同样的问题是:您期望的输入范围在0.2<U<0.7.

如何重写if-then语句如下:

if( (S >= 25 && S <= 75) && (S % 5 == 0) && (U > 0.2 && U < 0.7) ){ 
//...
}

这不仅使if语句的条件更易于阅读和理解,而且还消除了错误。现在应该可以了。代码的含义保持不变:S必须在25到75之间(包括这些数字),它应该可以被5整除,U应该在0.2到0.7之间。

顺便说一句,同样的错误也存在于你的代码的这一部分:

if( D < 0.35 && D < 0.45 ){...

我在下面修复了它:

if( D > 0.35 && D < 0.45 ){...

祝你好运!