1

我们应该创建一个接受 15 个电话号码的程序。所有数字由 8 位数字组成。固定线路以 17 开头,移动线路以 39 开头。Prog 应计算固定线路和移动线路的数量。此外,当用户输入负数时 prog 应该停止。

这是我的代码:

#include <iostream>
using namespace std;
void main ()
{

int n, c=1, cm=0, cf=0;

cout << "Enter a telephone number or enter a negative number to stop ";

while (c <= 15){
    cin >> n;

    if (n/1000000 == 39){
        c++;
        cm++;
    }

    else if (n/1000000 == 17){
        c++;
        cf++;
    }

    else cout << "Wrong telephone number" << endl;

    cout << "Enter the next telephone number or enter a negative number to stop ";
    cin >> n;

}

cout << "The number of fixed lines is " << cf << endl;
cout << "The number of mobile lines is " << cm << endl;

system ("PAUSE");

}

我有两个问题:

  1. 当用户输入负数时,我不知道如何结束程序。

  2. 程序在输入第二个号码后不会计算“输入下一个电话号码或输入负数停止”。

4

2 回答 2

3
  1. 当用户输入负数时停止循环,您需要使用break语句
  2. 检查你的逻辑是如何工作的:在循环结束时你输出字符串,询问数字并转到循环的开头,你再次询问数字

考虑以下代码:

int n, c=1, cm=0, cf=0;
while (c <= 15) {
    std::cout << "Enter the next telephone number or enter a negative number to stop ";
    std::cin >> n; // output prompt and ask for number only once per loop iteration
    if (n <= 0)
        break; // ends while loop if user entered incorrect value
    if (n/1000000 == 39)
        cm++, c++;
    else if (n/1000000 == 17)
        cf++, c++;
    else
        std::cout << "Wrong telephone number" << std::endl;
}
std::cout << "The number of fixed lines is " << cf << std::endl;
std::cout << "The number of mobile lines is " << cm << std::endl;
于 2013-11-08T18:20:12.397 回答
0

问题1:

  • 您可以检查否定并使用关键字break退出 while 循环。

问题2:

  • 地点:cout << "Enter a telephone number or enter a negative number to stop ";在while循环中。
于 2013-11-08T18:16:01.953 回答