簡體   English   中英

在C中檢查用戶輸入

[英]Checking user input in C

我想問一下:如何檢查用戶輸入(已與另一個數組存儲在數組中),我已定義...諸如此類:用戶將輸入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;}

要獲得用戶輸入,必須使用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;
}
#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;
   }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM