#include<iostream>
using namespace std;
void main()
{
int c=0, sum = 0, y;
cout << "press (1) to find the sum of 2 even numbers between 2 integers or press (2) to find all the prime numbers between 10 and 30,or press -1 to terminate";
cin >> c;
while (c != -1)
{
switch (c)
{
case (1) :
{int x=0;
cout << "enter 2 integers\n";
cin >> x >> y;
while (x<= y)
{
if (x % 2 == 0)
sum = sum +x;
x++;
}
cout << "sum is" << sum;
break;
}
case(2) :
{int counter = 30, counter2 = 1, nod = 0;
while (counter >= 10)
{
while (counter2 >= counter)
{
if (counter%counter2 == 0)
nod = nod + 1;
counter2++;
}
if (nod == 2)
cout << counter << " is prime number";
counter--;
}
break; }
default: cout << "wrong input";
}
}
}
如果按1则情况1工作正常,默认情况也很好。 哨兵循环也很好。 但是当我按2时它会将我切换到默认值。 怎么了? 我是c +的新手,但这个问题永远不会发生。
答案 0 :(得分:0)
你的代码工作正常(除了main必须返回int
):
可能只是你的案例2没有做你认为它做的事情。 因为这一行:
while (counter2 >= counter)
并且永远不会输入counter2 == 1
和counter == 30
您的while循环,而case (2)
将不会打印任何内容。
答案 1 :(得分:0)
你有一个永无止境的循环请检查:
#include<iostream>
using namespace std;
int main()
{
int c=0, sum = 0, y;
cout << "press (1) to find the sum of 2 even numbers between 2 integers or press (2) to find all the prime numbers between 10 and 30,or press -1 to terminate";
cin >> c;
while (c != 1)
{
switch (c)
{
case (1) :
{int x=0;
cout << "enter 2 integers\n";
cin >> x >> y;
while (x<= y)
{
if (x % 2 == 0)
sum = sum +x;
x++;
}
cout << "sum is" << sum;
break;
}
case(2) :
{int counter = 30, counter2 = 1, nod = 0;
while (counter >= 10)
{
cout << "hello im case 2";
while (counter2 >= counter)
{
if (counter%counter2 == 0)
nod = nod + 1;
counter2++;
}
if (nod == 2)
cout << counter << " is prime number";
counter--;
}
} break;
default: cout << "wrong input";
}
}
}
在这里查看: http://cpp.sh/5ond
答案 2 :(得分:-1)
do {
cin >> c;
switch {
case (1): {
// Your code
}
case (2): {
// Your code
}
case (-1): {
// Terminate
}
default: {
// Your code
}
}
} while (true);