使用“if”语句C ++更改结构变量

时间:2013-09-27 00:39:20

标签: c++ struct

我明天要完​​成一项家庭作业,要求我们提示用户输入许多车辆,驾驶里程,然后显示总费用。费用取决于里程数;如果它小于100,则为25美分/英里,如果超过100,则成本为100 + 15美分/英里。我创建了一个包含MilesPrice的结构。以下是我到目前为止的情况:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

struct Cars
{
    int Miles;
    double Price;
};

int main()
{    
    cout << "ENTER ALL OF THE CARS!";
    int NoCars;
    cin >> NoCars;
    Cars* info = new Cars[NoCars];
    int i;
    for (i=0; i<NoCars; i++)
    {
        cout << "How many miles were driven on this car? :";
        cin >> info[i].Miles;
        if(Miles > 100)
        {
            Price = 25 + 0.15 * Miles;
        } 
        else 
        {
            Price = 0.25*Miles;
        }
    }
    cout << "Here are the prices: \n";
    for(x=0, x < NoCars; x++)
    {
        cout << info[x].Price;
    }

    return 0;
}

正如您所看到的,我尝试使用Price语句修改if变量,但似乎我无法简单地访问它。有什么指针吗?

2 个答案:

答案 0 :(得分:1)

PriceMilesstruct Cars的字段,因此您需要像这样使用它们:

if(info[i].Miles > 100)
{
    info[i].Price = 25 + 0.15 * info[i].Miles;
} 
else 
{
    info[i].Price = 0.25 * info[i].Miles;
}

另外,在上一个for语句中,您使用的是未声明的x,可能是i的错字?顺便说一下,你那里也丢了一个分号:

for(x=0, x < NoCars; x++)
//     ^ should be ;

答案 1 :(得分:0)

我认为这个小程序中几乎没有错误:

1:if(Miles > 100)
    {
        Price = 25 + 0.15 * Miles;
    } 
    else 
    {
        Price = 0.25*Miles;
    }

也许你应该改变这样:

if(info[i].Miles > 100)
    {
        info[i].Price = 25 + 0.15 * info[i].Miles;
    } 
    else 
    {
        info[i].Price = 0.25*info[i].Miles;
    }

2:for(x=0, x < NoCars; x++)

也许你应该改变这样:

for(x=0; x < NoCars; x++)