在功能上遇到未定义的行为,以将数字添加到10以下
当输入包含逗号,点或非单数字符时,我在终端中遇到UB。我很困惑为什么会发生这种情况。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
float tizAlatti(int inputCount);
int main(){
int inputNumber;
printf("Number of input elements: ");
scanf("%d", &inputNumber);
if(inputNumber % 1 != 0 && (isdigit(inputNumber) == 0)){
printf("Error encountered.");
exit(1);
}
printf("\n%.2f", tizAlatti(inputNumber));
}
float tizAlatti(int inputCount){
float arr[inputCount], input = 0;
printf("\n");
for(int i = 0; i<inputCount; i++){
printf("Element %d: ", i+1);
scanf("%f", &arr[i]);
if(arr[i] < 10){
input+= arr[i];
}
}
return input;
}
在这里,我得到了“ H” 输入的输出。这不是其ASCII代码值,这是我的错误假设。
我弄清楚该问题在 Main()函数中的零件中放置在某个地方在主要输入中调用,但我不知道这个问题到底是什么。任何帮助都非常感谢!
I am encountering UB in the terminal with my current code when the input contains comma, dot or non-only-numeric character. I am confused why that is happening.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
float tizAlatti(int inputCount);
int main(){
int inputNumber;
printf("Number of input elements: ");
scanf("%d", &inputNumber);
if(inputNumber % 1 != 0 && (isdigit(inputNumber) == 0)){
printf("Error encountered.");
exit(1);
}
printf("\n%.2f", tizAlatti(inputNumber));
}
float tizAlatti(int inputCount){
float arr[inputCount], input = 0;
printf("\n");
for(int i = 0; i<inputCount; i++){
printf("Element %d: ", i+1);
scanf("%f", &arr[i]);
if(arr[i] < 10){
input+= arr[i];
}
}
return input;
}
Here I got this output for "h" input. It's not its ASCII code value, which was a false assumption by me.
I also got this output for "5.6" input.
I worked out that the issue lays somewhere in the if()
part in the main()
function, as the tizAlatti function gets invoked in the main for an input, but I don't know what this problem exactly is. Any help is highly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
scanf(“%d”,&amp; inputnumber)
norscanf(“%f”,&amp; arr [i]);
曾经阅读过这些字符* 1 ,因此它们保留在stdin
中,直到有东西读取它们为止。这也将阻止以下输入。AS
scanf(“%d”,&amp; inputnumber)
andscanf(“%f”,&amp; arr [i])
然后不要分配inputnumber
inputnumber < /code>或
arr [i]
,该值是不确定的,导致后续麻烦。检查
scanf()
的返回值,如果不是1,请退出或使用其他代码读取/消耗非数字输入,然后重试。更好的是,请使用
fgets()
读取一行用户输入,然后停止使用scanf()
,直到您知道为什么不好。*1
'。'
作为小数点的由scanf(“%f”,&amp; arr [i])
读取。Neither
scanf("%d", &inputNumber)
norscanf("%f", &arr[i]);
ever read these characters*1, so they remain instdin
until something does read them. This also blocks following input.As
scanf("%d", &inputNumber)
andscanf("%f", &arr[i])
then do not assigninputNumber
orarr[i]
, that value is indeterminant leading to subsequent trouble.Check the return value of
scanf()
and if not 1, exit or use other code to read/consume the non-numeric input and try again.Even better, use
fgets()
to read a line of user input and stop usingscanf()
until you know why it is bad.*1
'.'
as a decimal point is read byscanf("%f", &arr[i])
.