简体   繁体   English

为什么此for循环不执行?

[英]Why won't this for loop execute?

I'm making a simple program that gets the users balance from the entered ID. 我正在制作一个简单的程序,可以使用户从输入的ID中获得余额。 For some reason the for loop doesn't execute when an ID from the listof_ID array is entered: 由于某些原因,当输入listof_ID数组中的ID时,for循环不会执行:

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

int main()
{
    int cntr;
    int ID;

    int listof_ID[] = {001, 002, 003, 004, 005};
    float listof_BAL[] = {338.90, 745.87, 897.32, 665.36, 102.45};

    puts("**Check Your Balance** \n");
    printf("**Please Enter Your ID >> ");
    scanf("%d", &ID);
    for(cntr = 0; cntr > 5; cntr++)
    {
        if(ID == listof_ID[cntr])
        {
            puts("Your balance is ");
            printf("%.2f", listof_BAL[cntr]);
            break;
        }
    }

    return 0;
}
for(cntr = 0; cntr > 5; cntr++)

Should be 应该

for(cntr = 0; cntr < 5; cntr++)

The loop executes while the condition cntr > 5 is true. 在条件cntr > 5为真时执行循环。 If cntr starts at 0 then it is obviously not greater than 5, so the body of the loop never executes. 如果cntr0开始,那么它显然不大于5,因此循环的主体永远不会执行。

In your for loop, the first value of cntr = 0, which means that cntr < 5. But in the condition, you are checking if cntr > 5, which is not true. 在for循环中,cntr = 0的第一个值,这意味着cntr <5。但是在这种情况下,您正在检查cntr> 5,这是不正确的。 So, the loop does not start. 因此,循环不会开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM