简体   繁体   English

如何修改 c 程序,以便在用户输入非浮点输入时,向用户显示“无效输入”?

[英]How can I modify the c program such that if the user enters a non-float input,“invalid input” is shown to the user?

Here is the code:这是代码:

// c program to add 10 elements entered by the user
#include <stdio.h>
int main()
{
    int i;
    float elements[10]; //declaring the array
    float sum = 0;

    for (i = 0; i < 10; ++i)
    {
        printf("Enter element %d: ", i + 1); //getting the elements from  the user
        scanf("%f", &elements[i]);           //storing the elements
        sum += elements[i];                  //adding integers entered by the user to t   he sum variable
    }

    printf("sum of above entered elements is : %.4f", sum); //printing the sum to four decimal places
    return 0;
}

Do something like:执行以下操作:

  • Let the user input a string让用户输入一个字符串
  • Validate input on the string验证字符串上的输入
  • Convert it to a float if everything is fine.如果一切正常,将其转换为浮点数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM