如果我想输入一个字符到a,b,c的值,那么它会说"error",该怎么办?

what will i do if i want to enter a char to the value of a,b,c then it will say "error"?

本文关键字:的值 怎么办 error 输入 一个 如果 字符      更新时间:2023-10-16
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    double a,b,c,d,X,Y;
    float x1,x2;
    char ans,i;
    do
    {
         cout << "Welcome!" <<endl
              << "To my Simple Machine" <<endl
              <<endl
              << "Enter the value of a:" <<endl;
         cin >>a;
         cout << "Enter the value of b:" <<endl;
         cin >>b;
         cout << "Enter the value of c:" <<endl;
         cin >>c;
         d=b*b-4*a*c;
         x1=(-1*b+sqrt(b*b-4*a*c))/2*a;
         x2=(-1*b-sqrt(b*b-4*a*c))/2*a;
         X=-b/2*a;

如果用户将在 A、B、C 上输入字符,我想显示错误

         if(a==0)
         {
                 cout << "You are now solvin a Linear Eq'n" <<endl;
                 Y=-c/b;
                 cout << "The value of Y is:" <<Y<<endl
                      <<endl
                      << "Do you want to repeat?" <<endl
                      << "Loading...." <<endl;
         }
         else if(d==0)
         {
              cout << "You are now solving a Quadratic Eq'n" <<endl
                   << "The value of d is:" <<d<<endl
                   << "x1 is:" <<x1<<endl
                   << "x2 is:" <<x2<<endl
                   <<endl
                   << "Do you want to repeat?" <<endl
                   << "Loading...." <<endl;
         }
         else if(d>0)
         {
              cout << "You are now solving a Quadratic Eq'n" <<endl
                   << "The value of d is:" <<d<<endl
                   << "x1 is:" <<x1<<endl
                   << "x2 is:" <<x2<<endl
                   <<endl
                   << "Do you want to repeat?" <<endl
                   << "Loading...." <<endl;
         }
         else if(d<0)
         {
              cout << "You are now solving a Quadratic Eq'n" <<endl
                   << "The value of d is:" <<d<<endl
                   << "x1 is:" <<X<<"+"<<sqrt(-d)/2*a<<'i'<<endl
                   << "x2 is:" <<X<<"-"<<sqrt(-d)/2*a<<'i'<<endl
                   <<endl
                   << "Do you want to repeat?" <<endl
                   << "Loading...." <<endl;
         }
         cout.setf(ios::fixed);
         cout.setf(ios::showpoint);
         cout.precision(2);
    }while(ans=='y' ||ans=='Y');
         cout << "End of Program..." <<endl
                         << "Thank You!" <<endl;
    cin.get();
    cin.get();
return 0;
}

我无法编译它,因为它说 g++.exe不起作用

如果我

没看错,您想在用户输入浮点值以外的任何内容时显示一条消息?然后,您可以通过记住流可以用作布尔值来做到这一点,并记住例如输入运算符返回流。所以你可以做例如

if (!(cin >> a))
{
    std::cout << "Error: Illegal inputn";
}

要清除由非法输入设置的错误位,请使用std::basic_ios::clear .

您应该

将其存储在char变量中,检查它是否是数字条目,然后将其分配给double

double b;char tmpChar;
cout << "Enter the value of b:" <<endl;
cin >>tmpChar;
if ((tmpChar >= 'a' && tmpChar <= 'z') || (tmpChar >='A' && tmpChar <='Z'))
   error();