我头痛地尝试运行这段代码。我试图确定我输入的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,它打印出预期的输出。但是当我输入一个/ 6或6/a时,它会陷入逻辑错误,一个无限循环。它就像在if语句和while语句中的数据转换的某处出错一样。还是因为使用的数据类型错误?我无法追查可能出现的问题。有没有解决方案如何做到这一点?请帮忙。提前谢谢兄弟姐妹们。
你可以给你的代码添加注释吗?不知道发生了什么...... -/ – Swanand
'cin >> sym1'把一切都留在cin中,因为它是一个字符串,不管字符如何,它都会被接受......你可能想要看的是一个词法分析器。 –
Alexis Wilke stof?它会有所作为吗? –