2017-01-23 163 views
0

我需要从给定范围内的用户获取输入整数。我需要得到他们的低和高。但循环不停,我不知道为什么。我认为我的条件很好,但循环不会停止。它应该是什么获取用户输入并在需要时停止循环C

int  obtainNumberBetween (const char* descriptionCPtr, int low, int high) { 
    char line[MAX_LINE]; 
    int entry; 
// #define  MAX_LINE 256 

    // YOUR CODE HERE 
do 
    { 
    printf("Please enter the lowest number in the range (%d-%d):\n " ,RANGE_LOWEST ,RANGE_HIGHEST); 
    fgets(line, 256, stdin); 
    low = atoi(line); 
    printf ("The value entered is %d\n", low); 

    } 
    while ((entry < low) || (entry > high)); 

return(entry); 

} 

输出示例:

Please enter the lowest number in the range (0-32767): -6 
Please enter the lowest number in the range (0-32767): 1 
Please enter the highest number in the range (1-32767): 0 
Please enter the highest number in the range (1-32767): 32768 
Please enter the highest number in the range (1-32767): 512 
+1

什么入口在干什么?你在里面比较什么价值? –

+0

那么,用户输入需要低于“低”,或大于“高”,然后用户被要求另一个号码。用户最终输入一个合法的号码后,该函数返回该号码。 – yeny314

+2

low = atoi(line);你低覆盖,你是否打算写入?因为你没有做任何事情进入,但你的修改很低,因此你失去了最低的价值。 –

回答

0

entry变量未初始化。所以这行调用一个未定义的行为:

while ((entry < low) || (entry > high)) 

也许你应该用户输入分配给entry,而不是low

+0

但是,如果我这样做,我将如何获得高?我需要从用户那里得到2个整数,这是低和高 – yeny314

0

您需要为entry指定一个值。 循环不停止,因为entry尚未初始化,因此while循环的条件始终为真。

变化 low = atoi(line);

entry = atop(line); 

,然后while循环之后添加

low = atoi(entry); 

+0

你的意思是entry = atoi(line); ? – yeny314

+0

如何获得最高价值?一样的东西? – yeny314