在C中的数组实施范围 [英] Enforcing range in an array in C

查看:131
本文介绍了在C中的数组实施范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速,可能超基本问题。如果我宣布的10双阵列,并提示用户输入他们(介于1和10,很明显)指数有多少双想,我怎么会强制执行范围是多少?我想用if / else语句,但有强制执行的范围更优化的方式?

Quick, probably super basic question. If I declare an array of 10 doubles and prompt a user to input how many double they want in the index (between 1 and 10, obviously), how would I enforce that range? I assume with an if/else statement, but is there a more optimal way to enforce that range?

此外,可能真的很简单。我是新所以还不熟悉C ++或JavaScript。

Again, probably really simple. I'm new so not yet familiar C++ or JavaScript.

推荐答案

如果您在使用%(模)运算符包住要求的范围内的值另一种解决方案可能。

Another solution maybe if you wrap the value within the required range using % (modulo) operator.

int n;
int arr[10];
printf("Enter a number : ");
scanf("%d",&n);
printf("%d",arr[n%10]);

这位前pression N%10 总是会导致到9 0之间的值。

The expression n%10 will always result in a value between 0 to 9.

Edit(对于一个更好的验证):

#include<stdio.h>
main()
{
    int x, n;
    int arr[]={0,1,2,3,4,5,6,7,8,9,10,11,12};
    printf("Enter a number : ");
    if( scanf("%d",&n)!=1 )
    {
        printf("Not a valid integer!!");
        return;
    }
    n=(n<0)?-n:n;
    printf("%d",arr[n%10]);
}

这篇关于在C中的数组实施范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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