c - C 语言新手,循环问题

标签 c

我想在数组中输入 0 到 101 之间的值,尝试输入 0 或 101 将返回错误,但输入 1-100 之间的任何值将允许我输入第二个数字。

但是当我编写代码添加第二个数字时,我陷入了困境,循环一直在 1 中进行,我无法弄清楚我的错误。任何帮助将不胜感激

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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char letter;

int main() 
{
    int i;
    int grades[12] ;

    for ( i = 0; i < 12; i++) 
        do{//loops the following peice of code if values over 100 or less than 0 are entered 

            printf("Please Enter Grade 1:\n");
            scanf("%f", & grades[i]);
            if (grades > 100 || grades < 0)
                printf("Invalid Entry please enter another between 0 and 100:\n");
        }while(grades < 100 || grades > 0);
}

最佳答案

这里的错误是您将整个数组与一个值进行比较。您想要的是一个元素,另外您需要测试您是否超出了可接受的范围:

while(grades[i] > 100 || grades[i] < 0);

正如 Jonathan 在下面指出的那样,代码中的逻辑会测试其内部逻辑,这意味着只有有效的答案才会永远循环,这与您想要的相反。

关于c - C 语言新手,循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47339870/

相关文章:

C - 尝试将输入的未指定数量的数字转换为各自的单词

c - 嵌入式 C 中的信号量和可能的不可重入函数

c - 如何在linux上设置gcc编译.c文件的超时

c - 如何使用指针在 c 中编写自己的 strchr?

c - 为什么当我使用 copy_from_user 时,一些模糊字符添加到原始缓冲区?

c - 将文本文件读取到双向链表

c - getopt() 中的 optarg 始终为 null

c++ - 如何知道库是调试库还是发布?

c - "int *(*pfp) ();"在 C 中做什么?

c - 在 QNX 中使用 fork() 时如何确保子进程和父进程具有不同的地址空间