我在尝试运行我拥有的这段代码时感到头疼。我正在尝试确定我输入的float值是否将与float相同。这是我的编码。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    float x1, y1, x2, y2, x3, y3, percentage;
    string sym1, sym2;
    int count;

    cout<<"Enter the first fraction : ";

    do{
        cin>>x1>>sym1>>y1;

        if(x1 != float(x1) || sym1 != string(sym1) || y1 != float(y1))
        {
            cout<<"Please enter the correct fraction : ";
        }
        else if(sym1 != "/")
        {
        cout<<"Sorry. This is not a fraction. Please enter again : ";
        }
        else
        {
            break;
        }
    }while(x1 == float(x1) || sym1 == string(sym1) || y1 == float(y1));

    cout<<"Enter the second fraction : ";

    do{
        cin>>x2>>sym2>>y2;

        if(x2 != float(x2) || sym2 != string(sym2) || y2 != float(y2))
        {
            cout<<"Please enter the correct fraction : ";
        }
        else if(sym2 != "/")
        {
            cout<<"Sorry. This is not a fraction. Please enter again : ";
        }
        else
        {
            break;
        }
    }while(x2 == float(x2) || sym2 == string(sym2) || y2 == float(y2));

    x3 = x1 * x2;
    y3 = y1 * y2;

    percentage = (x3*100)/y3;

    cout<<x1<<"/"<<y1<<" and "<<x2<<"/"<<y2<<" is "<<x3<<"/"<<y3<<"\n";
    cout<<x3<<"/"<<y3<<" is "<<percentage<<"%";

    return 0;
}


我要更改的代码是这个

    do{
        cin>>x1>>sym1>>y1;

        if(x1 != float(x1) || sym1 != string(sym1) || y1 != float(y1))
        {
            cout<<"Please enter the correct fraction : ";
        }
        else if(sym1 != "/")
        {
        cout<<"Sorry. This is not a fraction. Please enter again : ";
        }
        else
        {
            break;
        }
    }while(x1 == float(x1) || sym1 == string(sym1) || y1 == float(y1));


看来,当我输入4/6或任何其他相关的分数格式时,它会正确读取。相同的去4 * 6,它打印出预期的输出。但是当我输入a / 6或6 / a时,就会陷入逻辑错误,无限循环。就像在if语句和while语句中的数据转换中的某处出错一样。还是因为使用的数据类型错误?我无法找到问题所在。有什么解决办法吗?请帮忙。在此先感谢兄弟姐妹们。

最佳答案

这些比较均无法返回false。

if(x1 != float(x1) || sym1 != string(sym1) || y1 != float(y1))
{
    cout<<"Please enter the correct fraction : ";
}


x1y1是浮点数,将它们强制转换为浮点数不会改变它们的值。 std::string比较运算符还会比较字符串的内容,因此此比较也将始终返回true。

您使用与循环条件相同的语句,这会导致无限循环。尝试在两种情况下仅使用if(sym1 != "/")(更好:仍然只对比较值进行一次评估,并将结果存储在布尔值中。当您以后进行某些更改而忘记在任何地方进行更改时,两次执行都会导致bug)。

有关operator>>工作方式的更多详细信息,请参见cppreference

引用:

直到C ++ 11:


  如果提取失败(例如,如果在预期数字的位置输入了字母),则保留值不变,并设置故障位。


从C ++ 11开始:


  如果提取失败,则将零写入值并设置故障位。如果
  提取导致该值太大或太小而无法容纳
  值,std :: numeric_limits :: max()或std :: numeric_limits :: min()
  写入并设置了故障位标志。

关于c++ - 使用数据类型转换来 float 的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18973367/

10-11 23:01
查看更多