How do I determine if a value is within a range?

人盡茶涼 提交于 2020-01-30 11:48:07

问题


I am relatively new to C, I have to do it for school unfortunately and I am having issues with it at the easiest exercises.

Here I have to check if a number is in a certain interval, for example between 4 and 6. I made it like this.

#include <stdio.h>

int main(){

  int i;

  printf("Value to check Interval \n");
  scanf("%s", i);
  if (i>4 && i<6){
    printf("%s Value is in first interval\n", i);
  }
}

The scanf to enter the number and check if it is in the interval. But even if I enter a number that is part of it, for example 5, the printf doesn't do anything. I tried also to add an else statement for numbers outside the interval, but also there the printf did not change anything.


回答1:


It is because you have declared i variable as int and you are taking input as string so when it is checking condition it is getting null value in i variable and not able to enter if block check below code

    #include <stdio.h>

    int main(){

      int i;
        printf("Value to check Interval \n");
        scanf("%d",&i);

      if (i>4 && i<6){
        printf("%d Value is in first interval\n", i);
      }
    }

try compiling your code without if condition i variable will return a null value



来源:https://stackoverflow.com/questions/54269344/how-do-i-determine-if-a-value-is-within-a-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!