2012-11-12 37 views
0
#include <iostream> 
#include <conio.h> 

using namespace std; 

int main() 
{ 
    int n; 
    char ans, cont; 
    ans = 'y'; 

    while (true){ 
     if (ans == 'y' || ans == 'Y'){ 
      cout << "Enter a price:" << endl; 
      cin >> n; 
      n++; 

      cout << "do you want to continue? y/n" <<endl; 
      cin >> ans; 

      switch (n) { 
       //Vat Prices 
       case 1: 
        if (n<300) 
         cout << "You have to pay" << endl << n * 1.1 << " $" << endl <<endl; 
        break; 

       case 2: 
        if (n==300) 
         cout << "You have to pay" << endl << (n * 1.05) * 1.1 << " $" << endl <<endl; 
        break; 

       case 3: 
        if (n>=301 && n <= 500) 
         cout << "You have to pay" << endl << (n * 1.1) * 1.1 << " $" << endl <<endl; 
        break; 

       case 4: 
        if (n>= 501 && n <= 1000) 
         cout << "You have to pay" << endl << (n * 1.2)*1.1 << " $" << endl <<endl; 

       case 5: 
        if (n>1000) 
         cout << "You have to pay" << endl << (n * 1.3)* 1.1 << " $" << endl <<endl; 
        break; 
      } 
     } 
    } 
    return 0; 
} 

如果我把n程序不会通过交换机,它好工作一个小时前,我不知道发生了什么如果使用其他与开关

+2

你是不是想用'ans'代替'n'? ...因为很明显,例如,如果'n == 5'(对于最后一种情况)'n> 1000'永远不会成立。 –

回答

1

这不是如何切换工作。既然你基于范围做出决定,你只需要一个简单的if/else if/else链。有关如何使用开关的更多信息,请阅读this

0

你可能想要把 cout < <“你想继续?y/n”<> ans;

在您的while循环结束。

此外,我还建议只是有它说

while (ans == 'y' || ans == 'Y') 

但是最大的问题是,你的switch语句只当n == 1。摆脱整个switch声明,只使用if s。

3

你的缩进也没有帮助你。那个switch语句并没有做你认为的事情。当你做这样的事情:

switch (n) { 
case 1: 
    //do stuff 
    break; 
case 2: 
    //do stuff 
    break 
default: 
    //do stuff 
} 

的1和2在上面的情况是n的,你接通的值,即当n == 1,它会做第一种情况;当n == 2它会做第二种情况;否则它会执行默认块。

if声明的情况下,声明完成了交换机尚未为您执行的任何操作。 1工作,因为当n == 1条件n < 300自动为真。但是,所有其他情况都依赖于n为1,2,3,4或5,结果,其他测试都不可能通过。

你真正想要的是:

if (n < 300) { 
    // do stuff 
} else if (n == 300) { 
    // do stuff 
} else if (n > 300) { 
    // do stuff 
} etc... 
+0

我在修改中修正了缩进。有人需要检查它。 – Tyzoid

+0

+1解释我懒得明确地说。很好的答案。考虑到这个问题的新手性质,澄清你所说的“你接通的n的价值”可能是明智的。 – jpm

0

switch语句只会打的情况下,如果输入的价格是1, 2, 3, 4 or 5。交换机不会如何使用它们,您最好使用控制结构。

if(n<300) 
    cout << "You have to pay" << endl << n * 1.1 << " $" << endl <<endl; 
else if(n==300) 
    cout << "You have to pay" << endl << (n * 1.05) * 1.1 << " $" << endl <<endl; 
else if(n <= 500) 
    cout << "You have to pay" << endl << (n * 1.1) * 1.1 << " $" << endl <<endl; 
else if (<= 1000) 
    cout << "You have to pay" << endl << (n * 1.2)*1.1 << " $" << endl <<endl; 
else 
    cout << "You have to pay" << endl << (n * 1.3)* 1.1 << " $" << endl <<endl; 

此外,您每次循环时只覆盖您的n变量。然后你增加1,n++。这没有多大意义。