这个正确的条件有什么问题? :)

时间:2012-03-02 11:57:08

标签: c if-statement conditional-statements

我发现这很奇怪。据我所知,这句话没有任何问题,但是当它运行时,无论我输入什么数字,它总是评估为假。

if(temp>=1 && temp<=5)

temp是一个整数,我只想成为1-5之间的数字。所以,语句的前半部分读取if(temp is equal to or greater then one AND if temp is less then or equal to 5).我认为如果你输入3,这应该返回true,因为它大于1且小于5但不是。我错过了什么? :)

EDIT 完成循环:

int temp;
int arrayStorlek=0;
int tempBytesIndex[5];

  for(;;){ 
     temp=getchar();
     if(temp=='n' || temp=='N'){
         printf("Du är nöjd");
         beraknaHand(kortHand);
         }
     else{
       printf("Hära \n%i\n ", temp);
       system("pause");   
       if( isdigit(temp)){
            if(temp<=5 && temp>=1){
                printf("temp är större än 0 och mindre än 5");
                tempBytesIndex[i++] = temp-'0';
                arrayStorlek++;
                }
            else
               printf("du måste ange ett intervall mellan 1-5");   
               }
       else if (temp=='\n' || temp==EOF){ 
            printf("Slut på inlästa filer");
              system("pause");
              break;
              }
       else
          printf("\n Du får bara ange siffror, eller ange N om du är nöjd");
}

打印变量temp时,即使输入3,它也会返回50以上的值。这怎么可能? :)

2 个答案:

答案 0 :(得分:3)

以下测试程序:

#include <stdio.h>
int main() {
    int temp = 3;
    if(temp>=1 && temp<=5) { printf("yes"); }
    else { printf("no"); }
}

打印“是”。所以......是的,你对这种情况的理解是正确的,显然你的其他一个假设是错误的。

答案 1 :(得分:1)

getchar返回int,但该数字代表字符的代码。我认为scanf更适合你,或者你必须将从getchar获得的char转换为int。