2的倍数条件不工作(反问题)

The multiples of 2 Condition is not working(Counter Problem)

本文关键字:问题 工作 条件      更新时间:2023-10-16

从技术上讲,我的这段代码是一个水壶模拟,但现在的问题是。当它达到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! %dn",counter);
        if( counter%2 == 0&& nWaterTemp >=20.0 ){
                      nWaterTemp+=1.5/2.0;  
            printf("The water temp is %.2fn",nWaterTemp); 
        }else if(counter%3==0){
            nWaterTemp+=2.0/3.0;
            printf("The water temp is %.2fn",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 COOLINGn");
    while(nWaterTemp>=0){
        counter2++;
        wait(1);
        printf("Ticking! %dn",counter2);
        if(counter2%3==0){
            nWaterTemp -=2.0/3.0;
            printf("The water temp is %.2fn",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 %.2fn",nWaterTemp);

这是让我感到困惑的部分,正如你在条件中看到的它应该每2秒增加一次温度值但事实是它每1秒改变一次有时每1秒改变一次请帮忙

你应该这样写:

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

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