【问题标题】:console exits loop with incorrect value in C控制台以 C 中的错误值退出循环
【发布时间】:2017-06-13 03:12:42
【问题描述】:

当输入 INCORRECT 值时,我有一个函数退出循环。

我希望函数在退出循环之前要求用户输入正确的值。

我将用户输入的hours 的值传递给函数wrongHours

如果用户要输入低于 0 或高于 23 的小时数,该函数应该要求用户再次输入一些内容,但它只是转到下一行?我是不是少了一面旗帜?

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <conio.h>

// function prototypes
int wrongHours(int n);


int main(void)
{

    int hours;
    int minutes;

    printf("Enter the first hour value (0 - 23): ");
    scanf("%d", &hours);

    while (wrongHours(hours)) {

        printf("Enter the first hour value (0 - 23): ");
        scanf("%d", &hours);
    }

    printf("\nEnter the first minute value (0 - 59): ");
    scanf("%d", &minutes);


    _getch();
    return 0;

} // end main

// function validates that hours are between 0 - 23
int wrongHours(int n) {
    int i;

        if (n < 0 || n > 23) {
            printf("Invalid data entered, try again!");
            return 0;
        }
    return 1;
}

【问题讨论】:

  • 它会跳过它,因为 while 循环在不正确的时间设置为 0,因此它永远不会执行里面的内容。尝试切换您的 wrongHour 回报。
  • wrongHours 你为什么有一个循环?您是否只想检查n 的值是否在023 之间?这只需要一行。
  • 你需要在scanf之后消费'\n'

标签: c while-loop


【解决方案1】:

我不知道你为什么要使用for循环,下面是一些格式化代码,请检查它是否满足你的需要

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <conio.h>

// function prototypes
int wrongHours(int n);

int main(void)
{
    int hours;
    int minutes;

    printf("Enter the first hour value (0 - 23): ");
    scanf("%d", &hours);

    while( wrongHours(hours)) {
        printf("Enter the first hour value (0 - 23): ");
        scanf("%d", &hours);
    }

    printf("\nEnter the first minute value (0 - 59): ");
    scanf("%d", &minutes);

   _getch();
    return 0;
} // end main

// function validates that hours are between 0 - 23
int wrongHours(int n) 
{
    if (n < 0 || n > 23) {
        printf("Invalid data entered, try again!");
        return 1;
    }
    return 0;
}

【讨论】:

  • 您可以将第一个循环设为do...while 循环以避免代码重复
  • 下面是一些格式化代码,嗯。 .压痕完全关闭!这不是“在 SO 中粘贴代码”的问题。
  • 请考虑编辑您的答案,添加对问题所在的解释以及修复的详细信息。
  • 这是我见过的最不一致的格式代码。帮自己一个忙,学习正确且一致地格式化您的代码。
猜你喜欢
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 2014-02-17
  • 1970-01-01
相关资源
最近更新 更多