if语句基于用户输入

时间:2014-10-07 01:05:04

标签: c++ visual-c++

我试图根据用户输入使用不同的if语句。然而它似乎只使用最终集。任何帮助都会非常感谢。

char type[20];
double weight;
double feed;


cout<< "Enter horse type:  ";
cin>>type;
cout << "Enter the horse weight in whole pounds:  "; 
cin>>weight; 
cout<<"Horse type: "<<type<<endl;
cout<<"Horse weight: "<<weight<<endl;

这是我的if语句。

  {
    if (type=="Light");
    if (weight >= 840 && weight <=1200) 
    feed = (3.0); 
    else if (weight< 840)
    feed = (3.3);
    else if (weight > 1200)
    feed = (2.5);
    }
    {
    if (type=="Large");
     if (weight >= 1100 && weight <=1300) 
    feed=(3.0);
    else if (weight < 1100)
    feed=(3.3);
    else if (weight > 1300)
    feed= (2.5);
    }
    {

    if (type=="Draft");
    if (weight >= 1500&& weight <=2200) 
    feed = (3.0); 
    else if (weight< 1500)
    feed = (3.3);
    else if (weight >2200)
    feed= (2.5); 
    }

    cout<<"Feed Amount "<<feed<<" pounds"<<endl;

再次感谢您的帮助

2 个答案:

答案 0 :(得分:3)

您无法使用==比较C风格的字符串(字符数组)。这比较了数组的地址,而不是它们的内容。

请改用std::string。用

替换第一行
std::string type;

您还需要修复if语句:

if (type == "Whatever")  // no ;
{
    // do stuff
}

答案 1 :(得分:0)

你在哪里:

{
if (type=="Light");

应该是:

if ( type == "Light" )
{

和Draft和Large相同。无论if如何,您实际执行的操作都是不执行任何操作,并始终执行以下代码。

另外(如Mike Seymour所述)将char type[20];更改为std::string type;。如果你真的必须坚持char,那么你还需要改变你的比较。

如果您的编译器支持C ++ 14,那么:

if ( type == "Light"s )

否则:

if ( type == std::string("Light") )   

对于上述任何一种情况,您需要在文件顶部显示#include <string>