arrays - 在 C 编程中 - 如何用非数字输入打破 for 循环
问题描述
试图制作一个需要例如的C程序。浮点数组中的 5 个用户输入。然后打印数组并打印另一个累积数字的数组。它工作正常,但是如果输入是非数字的,我如何打破输入并打印“不是数字”?
#include <stdio.h>
int main(){
float i,sum;
sum=0;
const int ARRAYSIZE = 5;
float array1[ARRAYSIZE];
printf("Input a number (a total of %d numbers is needed):\n", ARRAYSIZE);
fflush(stdout);
for(int i = 0; i < ARRAYSIZE; i++){
scanf("%f", &array1[i] );
}
for(int i = 0; i < ARRAYSIZE; i++){
printf("You typed in: %.2lf\n",array1[i]);
}
for(int i = 0; i < ARRAYSIZE; i++){
sum+=array1[i];
printf("The accumulated value if the input is: %.2lf\n", sum);
}
return 0;
}
解决方案
检查scanf的返回值
if(scanf("%f", &array1[i] ) != 1)
{
printf("Invalid number\n");
/* so more code */
}
推荐阅读
- java - 如何在对象列表中查找某些字段的重复项?
- typescript - 应该如何构建打算通过 git url 安装的 Typescript 库?
- java - 如何连接字符而不是添加数值
- javascript - 在谷歌电子表格中值从 TRUE 变为 FALSE 后,有没有办法停止 COUNTIF 函数?
- google-cloud-pubsub - DataflowTemplates debezium 连接器问题
- scikit-learn - 评估缩放的 RMSE
- javascript - Jquery mousedown 没有在数据表上触发
- c++ - Painter 在继承的 QOpenGLWidget 类上不活动
- prestashop-1.7 - 在 Prestashop 1.7.6.8 中查找多个类别的产品
- material-ui - 使用 Rollup 将 Svelte Material UI 与自定义 SCSS 结合起来的麻烦