首页 > 解决方案 > 在 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;
}

标签: arrayscfor-loop

解决方案


检查scanf的返回值

 if(scanf("%f", &array1[i] ) != 1)
 {
     printf("Invalid number\n");
     /* so more code */
 }

推荐阅读