Enforcing range in an array in C

耗尽温柔 提交于 2019-12-11 09:19:56

问题


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?

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


回答1:


Get that no. of elements from user till that no. is not within your range.

Say n is number that you want in range 1 to 10.

Solution:

int n = 0;
while(n<1 || n>10)    {
    printf("Enter Correct value on n i.e. within range 1 to 10:\t");
    scanf("%d", &n);
}



回答2:


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

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

Edit (for a better validation):

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



回答3:


First you should read the documentation because this is a very basic example.

Second avoid requesting code here. You should always try to found solution then post your code and your error here to correct it.

You can try this:

#include<stdio.h>

int main(){
    int n = 0;
    while(!(n > 1 && n < 10)){
        printf("Enter an integer between 1 and 10: \n");
        scanf("%d", &n);
    }
}


来源:https://stackoverflow.com/questions/22433458/enforcing-range-in-an-array-in-c

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