gpt4 book ai didi

检查输入是否为数字、是否带小数点、或正/负

转载 作者:行者123 更新时间:2023-11-30 17:03:02 27 4
gpt4 key购买 nike

因此,我们被要求创建一个程序,使用户能够从 1-6 个有关矩阵运算的选项中进行选择。在每个用户的输入中,我们需要检查该输入是否适合要完成的操作(程序应该接受整数或 float ,正数或负数)。如果不满足上述条件,我们将要求用户再次输入另一个值,直到用户正确输入。

这是我的程序的片段:

printf("[A] You chose Matrix Addition\n");
printf("How many columns would you like?\n");
fgets(rows,sizeof(rows),stdin);
r=atoi(rows);
printf("How many rows would you like?\n");
fgets(columns,sizeof(columns),stdin);
c=atoi(columns);
printf("Enter the elements of first matrix\n");

for (e = 0; e < c; e++) {
for (f = 0; f < r; f++) {
printf("Element [%d][%d]:\n",e,f);
fgets(elem1,sizeof(elem1),stdin);
a=atof(elem1);
first[e][f]=a;
}
}

printf("Enter the elements of second matrix\n");

for (e = 0; e < c; e++) {
for (f = 0; f < r; f++) {
printf("Element [%d][%d]:\n",e,f);
fgets(elem2,sizeof(elem2),stdin);
b=atof(elem2);
second[e][f]=b;
}
}


printf("Sum of entered matrices:-\n");
for (e = 0; e < c; e++) {
for (f = 0 ; f < r; f++) {
sum[e][f] = first[e][f] + second[e][f];
printf("%.3f\t", sum[e][f]);
}
printf("\n");
}

我的问题是,我应该做什么才能(1)检查输入是否合格以及(2)如何要求用户再次输入另一个。

*我们不被允许使用 scanf 和其他“不安全”字符串函数,例如 put、gets、strlen 等。*上面的程序已经仅适用于整数,并且它不会告诉用户的输入是否无效。我怎么做?谢谢。

最佳答案

您可以这样做:

// I am providing just hint..
do {
printf("Enter Element [%d][%d]:\n",e,f);
fgets(elem1,sizeof(elem1),stdin);
a=atof(elem1);
}while(!notDesiredValue(a));

现在自己实现 notDesiredValue(flaot number) 来匹配您想要的条件......这有帮助吗......

关于检查输入是否为数字、是否带小数点、或正/负,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36291318/

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