首页 > 解决方案 > 我的程序不会停止执行 if 语句但条件不满足

问题描述

它应该是 x 轴上从 1 到 6 和 y 轴上从 1 到 5 的乘法表,所以我有这个 if 语句,一旦乘法达到 6 就应该跳转到 nezt 行,但它会继续执行甚至尽管我重置了其中要满足的条件。

#include <stdio.h>
#include <stdlib.h>
int main(){
int mult = 1;
int check = 0;
int res;
while(mult != 6){


        if (check <= 6){
            res = mult * check;
            printf("%d ",res);
            check ++;
        }
        if (check > 6 ){
            printf("\n ");
            check = 0;
        }

}}

标签: cif-statementvariableswhile-loop

解决方案


if语句使您执行或不执行块。

例如,在您的代码中:

if (check <= 6){
    res = mult * check;
    printf("%d ",res);
    check ++;
}
if (check > 6 ){
    printf("\n ");
    int check = 0;
}

第一个块将在 when 执行check <= 6,第二个块将执行check > 6... 但while循环中的条件是mult != 5... 并且您永远不会修改mult,因此条件始终为真。

因此,除了 uZuMaKioBaRuTo 对check变量的注释之外,您还需要递增mult

if (check > 6 ){
    printf("\n ");
    check = 0;
    mult++;
}

推荐阅读