将函数调用到C中的其他函数

时间:2017-07-02 23:22:47

标签: c function return

我有一个函数来验证数字是一个整数,然后我试图将此函数调用到另一个验证该数字是否在极限上的函数。首先,它不返回值,它返回扫描整数,我该如何解决?然后它重要的是我输入的值,10总是iVal。为什么?

 printf("Enter an integer between 10 and 20: ");
       iVal = getIntLimited(10, 20);

       printf("Your entered %d\n", iVal);

void flushKeyboard(void){
   char enter;
   do{
      scanf("%c", &enter);
   } while (enter != '\n');

}

int getInt(void){
   int  value;
   char nl;

   do{
      scanf("%d%c", &value, &nl);

      if (nl != '\n'){
         flushKeyboard();
         printf("Invalid integer, please try again: ");
         return value;      
      }

   } while (nl != '\n');
}

int getIntLimited(int lowerLimit, int upperLimit){

   int iVal;
   getInt() == iVal;

   if ((getInt() > lowerLimit) && (getInt() < upperLimit)){
      return iVal;
   }
   else{
   printf("Invalid value, %d < value > %d: ", lowerLimit, upperLimit);
   printf("\n");
   }
}

2 个答案:

答案 0 :(得分:1)

正如Vlad from Moscow所指出的,您需要将输入分配给变量并将其返回。

您的getInt()功能应该类似于:

int getInt(){
    int value;
    char nl;
    do{
        scanf("%d%c", &value, &nl);
        if (nl != '\n'){
            flushKeyboard();
            printf("Invalid integer, please try again: "); 
        }
    }while (nl != '\n');
    return value; //now you're returning the last scanned valid value!
}

此外,您还要三次调用getInt()功能:

1)当你&#34;进入&#34;你的getIntLimited()功能。

2)当您测试getInt() > lowerLimit

3)当您测试getInt() < upperLimit

由于参数lowerLimitupperLimit已经传递给函数getIntLimited(int lowerLimit, int upperLimit),因此您不需要为它们获取值。因此,我将您的getIntLimited(int lowerLimit, int upperLimit)功能更改为:

int getIntLimited(int lowerLimit, int upperLimit){
    int value;
    value = getInt(); //assign the input value to a variable
    if(value > lowerLimit && value < upperLimit){
        return value; //now you're returning the value that you got on getInt()
    }
    else{
        printf("Invalid value, %d < %d > %d: ", lowerLimit, value, upperLimit);
        printf("\n");
   }
   return value; //now you're able to check for this value on the first printf: printf("Your entered %d\n", iVal);
}

答案 1 :(得分:0)

希望这种方式适合你

void flushKeyboard(void){
   char enter;
   do{
      scanf("%c", &enter);
   } while (enter != '\n');

}

int getInt(void){

   int  value;

   scanf("%d", &value);
   return value;
}


int getIntLimited(int lowerLimit, int upperLimit){

   int iVal;
   iVal = getInt();
   printf(" %d \n", iVal);

   if ( ( iVal > lowerLimit ) && ( iVal < upperLimit )){
      printf("OK in bound\n"); 
      return iVal;
   }

   else{

        printf("Invalid value, %d < value > %d: ", lowerLimit, upperLimit);
        printf("\n");
        exit(0);
    }

}


int main()
{

   printf("Enter an integer between 10 and 20: ");
   int iVal = getIntLimited(10, 20);

   printf("Your entered %d\n", iVal);

}   

此外,您可以使用woz(上面的帖子)getInt(),代码功能不会改变。