首页 > 解决方案 > 使用 const 字面量的初学者 C++ 投票程序

问题描述

我在另一个论坛上遇到的这个程序是一个投票程序,有人在编译时遇到问题。给出的任何答案都与程序员想要的不符。所以我在这里尝试自己编辑代码后得到一些有效的答案。

我当前遇到的问题是当我输入变量时,它仍然运行无限循环。在我输入 5 票之前,我没有正确地执行设计以执行哪些操作?

#include <iostream>

using namespace std;

const int ev = 5; //max. # of votes
int votesA = 0, votesB = 0, votesC = 0, spoiltvotes = 0; //total votes already initialized globally
int vote; //input variable

int main()
{
    //loop over the voting stations
    int i;
    for(i = 0; i <= ev; i++)
   
   {
    //loop over the votes
    cout << "Enter your vote: \t";
    cin >> vote;
    while(vote <= 5)
    {

        switch(vote)
        {
            case 1: votesA++;
            break;

            case 2: votesB++;
            break;

            case 3: votesC++;
            break;

            default: spoiltvotes++;
        }

    }
   } 
    //display results neatly
    cout << "# of votes for candidate A: \t" << votesA;
    cout << "\n # of votes for candidate B: \t" << votesB;
    cout << "\n # of votes for candidate C: \t" << votesC;
    cout << "\n # of spoilt votes: \t" << spoiltvotes;

    return 0;
}

更新结果:我已经修复了无限循环,但由于某种原因,循环仍在迭代 6 次而不是 5 次,这给了我大量的数字而不是个位数。

#include <iostream>

using namespace std;

int main()
{
   const int ENDvote = 5; //max. # of votes

    //loop over the voting stations
    int vote;
    int spoiltvotes;
    for(vote = 0; vote >= ENDvote; vote++)
    cout << "1. Candidate A\t 2. Candidate B\t 3. Candidate C" << endl;
   
   {
    //loop over the votes
    cout << "Enter your vote: \t";
    cin >> vote;

        switch(vote)
        {
            case 1:
            cout << "# of votes for candidate A:\t" << vote;
            break;

            case 2:
            cout << "# of votes for candidate B:\t" << vote;
            break;

            case 3:
            cout << "# of votes for candidate C:\t" << vote;
            break;

            default:
            cout << "# of spoilt votes:\t" << spoiltvotes;
            break;
        }
   } 

    return 0;
}

标签: c++switch-statementconstantsliterals

解决方案


您的代码有一个明显的问题。当你进入你的 for 循环时:'for(i = 0; i <= ev; i++)' 你会得到 'cin>>vote;' 当您获得投票时,如果 'vote<=5' 由于 while 循环,循环将永远持续下去。一旦你进入 while 循环,投票永远不会改变。因此,如果满足 while 循环条件,它将始终为真,因为(再次)投票不会改变。

弗雷德·拉尔森(Fred Larson)基本上说了我的话。

我是堆栈溢出的新手,所以你认为我应该做的任何事情,请告诉我。


推荐阅读