如何确定一个值是否在范围内? [英] How do I determine if a value is within a range?

查看:145
本文介绍了如何确定一个值是否在范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C还是比较陌生,很不幸,我必须上学去上课,并且在最简单的练习中遇到问题。

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.

在这里,我必须检查一下如果一个数字在一定间隔内,例如4到6。我是这样的。

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);
  }
}

scanf 输入数字并检查它是否在间隔中。但是,即使我输入了一部分数字,例如5, printf 也不起作用。我还尝试为间隔之外的数字添加else语句,但是 printf 并没有改变任何内容。

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.

推荐答案

这是因为您已将 i变量声明为int ,而将输入作为 string ,因此在检查条件时会在 i变量中获取 null 值,并且无法输入if阻止检查以下代码

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);
      }
    }

尝试编译您的代码,如果条件i变量不会返回空值

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

这篇关于如何确定一个值是否在范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆