在C中检查用户输入

时间:2015-03-10 19:20:18

标签: c arrays

我想问一下:如何检查用户输入,这是与另一个数组存储在数组中,我已经定义了... 这样的事情:用户将给出输入10,20,5,我需要检查,如果是来自这个数组{5,10,20,50}

任何帮助赞赏:)。感谢

#include <stdio.h>
#include <stdlib.h>

int main ()
{
float bill;  
int notes[] = {100, 50, 20, 10, 5, 2, 1, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01};
printf("Enter value of your bill: ");
scanf("%f",&bill);
if (bill<0 || bill>10000)
{
return -1;
}

else 
{
for (int i=0; i<8;i++)
{
if (bill!=notes[i])
    {
    break;
    }
    }
    }





   return 0;}

2 个答案:

答案 0 :(得分:2)

要获得用户输入,您必须使用scanf()功能。这是一个例子,它要求三个单独的数字。

#include <stdio.h>

int main(void) { 
    int one, two, three;
    printf("Enter first number: ");
    scanf("%d", &one);
    printf("Enter second number: ");
    scanf("%d", &two);
    printf("Enter third number: ");
    scanf("%d", &three);

    printf("one: %d, two: %d, three: %d\n", one, two, three);
    return 0;
}

将产生以下内容:

Enter first number: 1
Enter second number: 2
Enter third number: 3
one: 1, two: 2, three: 3

以下是使用scanf的另一种方法,但用户必须更具体地说明他们如何回答提示。

#include <stdio.h>

int main(void) { 
    int one, two, three;
    printf("Enter three numbers separated by a comma: ");
    scanf("%d,%d,%d", &one, &two, &three);

    printf("one: %d, two: %d, three: %d\n", one, two, three);
    return 0;
}

将产生以下内容:

Enter three numbers separated by a comma: 1,2,3
one: 1, two: 2, three: 3

更新:因为您发布的代码显示了您知道scanf的工作原理。

要搜索数组,必须使用for循环。

#include <stdio.h>

int main(void) { 
    float n = 100;
    int numbers[] = {5, 10, 20, 50, 100, 200, 500};

    int i;
    for (i = 0; i < 7; i++) {
        if (n == numbers[i]) {
            printf("Matching index for %f at %d\n", n, i);
        }
    }

    return 0;
}

答案 1 :(得分:0)

#include<stdio.h>
int main(){
  int inp,i,j;
  int foo=0;
  int arr[]={5,10,20,30};
     for(j=0;j<3;j++){
       scanf("%d",&inp);
       for(i=0;i<4;i++)
       {
          if(inp == arr[i])
          {
              foo=1;
              break;
          }
       }
       if(foo==0)
        break;
   }

}
相关问题