2013-09-24 28 views
0

我头痛地尝试运行这段代码。我试图确定我输入的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语句中的数据转换的某处出错一样。还是因为使用的数据类型错误?我无法追查可能出现的问题。有没有解决方案如何做到这一点?请帮忙。提前谢谢兄弟姐妹们。

+1

你可以给你的代码添加注释吗?不知道发生了什么...... -/ – Swanand

+0

'cin >> sym1'把一切都留在cin中,因为它是一个字符串,不管字符如何,它都会被接受......你可能想要看的是一个词法分析器。 –

+0

Alexis Wilke stof?它会有所作为吗? –

回答

1

任何这些比较都没有办法返回false。

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

x1y1是花车,并铸造他们漂浮在任何方式不会改变自己的价值。 std::string比较运算符也比较字符串的内容,所以这种比较也总是返回true。

您正在使用与您的循环条件相同的语句,从而导致无限循环。对两种情况尝试只使用if(sym1 != "/")(更好的是:只比较一次比较结果,并将结果存储在布尔值中。当您稍后更改某些内容并忘记将其更改时,做两次操作会导致错误。

有关operator>>如何工作的更多详细信息,请参阅cppreference

引用:

直到C++ 11:

如果提取失败(例如,如果输入了字母,其中数字预计)值留未修饰的和failbit被设置。

由于C++ 11:

如果提取失败,零被写入值和failbit被设置。如果 提取的结果值太大或太小而不适合 值,则写入std :: numeric_limits :: max()或std :: numeric_limits :: min() ,并设置failbit标志。

+0

如果数值不是浮点数,我应该如何比较x1和y1的数字?例如我宣布他们为 'float x1,y1;',我将如何使它必须与我声明的数据类型相等?这就是为什么我把它做成'x1!= float(x1)',这样如果变量的值不是浮点数据类型,它将返回false。但仍然无济于事。 –

+0

float中不能有非浮点数据。这个比较的唯一原因是错误的,当值是'NaN'时,但这不是这里的情况。 – Hulk

+0

好吧。我会再试一次并回到你身边。当它工作时,我会告诉你这段代码。谢谢:) –