FOR循环和IF语句的问题

时间:2013-03-10 18:35:07

标签: loops if-statement for-loop repeat

尝试显示每个订购组合的价格和总价格。不知道为什么它不会在A,B和C中存储值。新手程序员在这里,所以很容易。 if语句有问题已经有一段时间了,所以显然我正在做整个if语句错误。

#include <iostream>
using namespace std;
int main( )
{
 int group = 0;
 char combo = ' ';
 int A = 0;
 int B = 0;
 int C = 0;
 double total = 0.0;
 cout << "How many customers are in the group? ";
 cin >> group;
 for (int counter = 0; counter < group; counter = counter + 1)
 {
    cout << "Enter combo ordered: ";
    cin >> combo;
    if (combo = A)
    {
        A = A + 1;
        cout << "Enter combo ordered: ";
        cin >> combo;
    }
    else if (combo = B)
    {
        B = B + 1;
        cout << "Enter combo ordered: ";
        cin >> combo;
    }
    else if (combo = C)
    {
        C = C + 1;
        cout << "Enter combo ordered: ";
        cin >> combo;
    }
    total = A*6 + B*6.25 + C*5.75;
 }
 cout << "# of Combo A ordered: " << A << endl;
 cout << "# of Combo B ordered: " << B << endl;
 cout << "# of Combo C ordered: " << C << endl;
 cout << "Total price: $" << total << endl;
 system("pause");
 return 0;
}

2 个答案:

答案 0 :(得分:3)

For循环应为for (int counter = 0; counter < group; counter++)

if语句应使用==进行相等。 =仅用于分配。

您的if语句需要引用您要比较的字符:if (combo == 'A') {。您也可能需要以字符数组的形式访问组合,如下所示:if (combo[0] == 'A') {

答案 1 :(得分:1)

我认为你可能需要调整一些事情;当您使用double计算int并且没有理由不在此处使用double时,一些编译器不喜欢它,因为程序很小。还有一些语法错误(即使用=而不是==)。您是否尝试过以独立方式显示输出?类似的东西:

main(){
double A = 1;
double B = 2;
double C = 3;
double total = A*6 + B*6.25 + C*5.75;

 cout << "# of Combo A ordered: " << A << endl;
 cout << "# of Combo B ordered: " << B << endl;
 cout << "# of Combo C ordered: " << C << endl;
 cout << "Total price: $" << total << endl;
 system("pause");
 return 0;
}

您的更正代码:

#include <iostream>
using namespace std;
int main( )
{
 int group = 0;
 char combo = ' ';
 double A = 0;
 double B = 0;
 double C = 0;
 double total = 0.0;
 cout << "How many customers are in the group? ";
 cin >> group;
 for (int counter = 0; counter < group; counter++)
 {
    cout << "Enter combo ordered: ";
    cin >> combo;
    if (combo == 'A')
    {
        A++;
    }
    else if (combo == 'B')
    {
        B++;
    }
    else if (combo == 'C')
    {
        C++;
    } 
    cout << "Enter combo ordered: ";
    cin >> combo;       
 }

 total = A*6 + B*6.25 + C*5.75;

 cout << "# of Combo A ordered: " << A << endl;
 cout << "# of Combo B ordered: " << B << endl;
 cout << "# of Combo C ordered: " << C << endl;
 cout << "Total price: $" << total << endl;
 system("pause");
 return 0;
}

我还会显示group的值,以确保if循环至少运行一次。这里有几个故障点我会单独测试。


修改

也许测试一下:

#include <iostream>
using namespace std;
int main( )
{
 int group = 0;
 cout << "How many customers are in the group? ";
 cin >> group;
 for (int counter = 0; counter < group; counter++)
 {
    cout << "Test success";
 }

看看你是否进入了for循环。