Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用相同的功能验证两个不同的问题_C - Fatal编程技术网

C 使用相同的功能验证两个不同的问题

C 使用相同的功能验证两个不同的问题,c,C,我遇到了一个问题,试图找出如何使用相同的功能(验证),验证2个不同的数字输入,使用2个不同的问题 int validate(int low, int high) { int flag = 0, number = 0; do { printf("Enter maximum value between %d and %d: ", low, high); scanf("%d", &number); if (number

我遇到了一个问题,试图找出如何使用相同的功能(验证),验证2个不同的数字输入,使用2个不同的问题

int validate(int low, int high) {
    int flag = 0, number = 0;

    do 
    {
        printf("Enter maximum value between %d and %d: ", low, high);
        scanf("%d", &number);
        if (number <= low || number > high) 
        {
            printf("INVALID! Must enter a value between %d and %d: ", low, high);
            scanf("%d", &number);
        }
        else {
            flag = 1;
        }
    } while(flag == 0);
    return number;
}
当我第二次调用
validate()
时(返回
num2
),我需要它请求一个数量的数字

任何帮助都将不胜感激。

理想情况下,您的validate()应该有另一个参数,表示它实际要做什么。 类似于
int验证(int-low、int-high、int-type)

然后打开类型以执行各种操作。但是我建议您更改函数的名称,因为validate不太合适。e、 g.
numGenEngine
其中类型表示步骤1、步骤2等

考虑到您需要完整的函数定义,您可以使用静态变量

int validate(int low, int high) {
    static int step = 0;
    int flag = 0, number = 0;

    if (step == 0) {
        // the first thing
    } else if (step == 1) {
        // the other thing
            // to reuse the function for the next set of operations
            // reset step to -1 here
    }

    step++;
    return number;
}

如果您仅限于此函数签名,则可以使用内部静态标志

您的函数同时执行输入和验证(而不仅仅是验证)。您的输入代码应检查
scanf()
是否成功;如果不是,你必须决定怎么做。不清楚为什么要使用非对称测试(
if(数字高)
);使用

int validate(int low, int high) {
    static int step = 0;
    int flag = 0, number = 0;

    if (step == 0) {
        // the first thing
    } else if (step == 1) {
        // the other thing
            // to reuse the function for the next set of operations
            // reset step to -1 here
    }

    step++;
    return number;
}