首页 > 解决方案 > for循环中的计数器不能通过增加2来正常工作

问题描述

我正在做一个非常基本的 C 作业。我需要制作一个游戏,让计算机生成一个随机数并让用户尝试猜测它。用户有 5 次尝试,我试图通过 for 循环给出。但是在每个循环上,尝试减少 2 而不是 1。我无法找出我在这里缺少的东西。我的代码:

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


int main(void) {
    
    int counter;
    int prediction;
    int number;
    
    srand(time(NULL));
    number = 1 + (rand() % 100);
    
        
    for ( counter=1; counter<=5; counter++ ) {
        
        printf("\nGuess my number from 1 to 100: \n");
        scanf("%d", &prediction);
        
        if (prediction < number) {
            printf("My number is greater than your guess. \n");
            printf("You have %d attempts left \n", (5-counter) );
            counter++;
        }
        
        if (prediction > number) {
            printf("My number is smaller than your prediction. \n");
            printf("You have %d attempts left \n", (5-counter) );
            counter++;
        }
        
        if (prediction == number) {
            printf("Congratulations! You guessed my number correctly! \n");
            
            break;  
        }
    }
    
    return 0;
}

标签: cfor-loop

解决方案


您将计数器增加两次:一次在两个if块中,一次在for循环线本身。删除循环体中的额外增量:

    if (prediction < number) {
        printf("My number is greater than your guess. \n");
        printf("You have %d attempts left \n", (5-counter) );
    }
    
    if (prediction > number) {
        printf("My number is smaller than your prediction. \n");
        printf("You have %d attempts left \n", (5-counter) );
    }

推荐阅读