gpt4 book ai didi

c++ - 2 条件的倍数不起作用(反问题)

转载 作者:行者123 更新时间:2023-11-28 08:16:37 26 4
gpt4 key购买 nike

从技术上讲,我的这段代码是一个水壶模拟,但现在的问题是。当它到达 20.00 时,它的代码不起作用

#include<stdio.h>
#include<stdlib.h>
#include<cstdlib>
#include<time.h>


//Global Declaration for waterTemperature
double nWaterTemp;

//Function for seconds :)
void wait ( int seconds ){
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {
}
}

//Function for increasing of hit of Kettle
void behaviourOn(){


int counter = 1;

while(nWaterTemp <=100.0){

wait(1);
printf("Ticking! %d\n",counter);
if( counter%2 == 0&& nWaterTemp >=20.0 ){
nWaterTemp+=1.5/2.0;
printf("The water temp is %.2f\n",nWaterTemp);

}else if(counter%3==0){
nWaterTemp+=2.0/3.0;
printf("The water temp is %.2f\n",nWaterTemp);
}else if(nWaterTemp == 20.0){
system("cls");
printf("THE KETTLE IS NOW ON!\n");
}
counter++;
}
}

//Function for Envinronment
void environment(){
int counter2 = 0;

system("cls");
printf("THE WATER IS NOW COOLING\n");
while(nWaterTemp>=0){
counter2++;
wait(1);
printf("Ticking! %d\n",counter2);

if(counter2%3==0){
nWaterTemp -=2.0/3.0;
printf("The water temp is %.2f\n",nWaterTemp);
}

}
}

//main
int main(void){
behaviourOn();
environment();
system("pause");
}

你看,如果水温不高于 20.00,它只会每 2 秒增加一次,但在我的代码中,有时它的值每 1 秒变化一次,也有时每 2 秒变化一次更改...此代码中的错误是什么?

if( counter%2 == 0&& nWaterTemp >=20.0 ){//THe equation changes if it reach 20.00, and the heat increases every 2 seconds
nWaterTemp+=1.5/2.0;
printf("The water temp is %.2f\n",nWaterTemp);

这就是让我感到困惑的部分,正如您在条件中看到的那样,如果应该每 2 秒增加一次温度值,但问题是它每 1 秒变化一次,然后有时每 1 秒变化一次,请帮忙

最佳答案

你应该这样写:

 if( nWaterTemp >=20.0 ) {
if (counter%2 == 0) {
nWaterTemp+=1.5/2.0;
printf("The water temp is %.2f\n",nWaterTemp);
}
} else if ...

否则当counter % 2 != 0时,它会做错事

关于c++ - 2 条件的倍数不起作用(反问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7538852/

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