试图运行我拥有的这段代码时我很头疼。我试图确定我输入的浮点值是否与浮点数相同。这是我的编码。
#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,它打印出预期的输出。但是当我输入 / 6 或 6 / a 时,它进入逻辑错误,一个无限循环。它就像在 if 语句和 while 语句中的数据转换中的某个地方是错误的。还是因为使用的数据类型错误?我无法追踪问题可能是什么。有没有关于如何做到这一点的解决方案?请帮忙。先谢谢各位兄弟姐妹了。