gpt4 book ai didi

在 C 中检查用户输入

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:44 24 4
gpt4 key购买 nike

我想问:如何检查用户输入,它与另一个数组存储在一个数组中,我已经定义了......像这样:用户将输入 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;
}

关于在 C 中检查用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28972305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com