【问题标题】:Why isn't it printing properly?为什么打印不正确?
【发布时间】:2016-01-30 03:53:51
【问题描述】:
#include <iostream>
#include <iomanip>

using namespace std;

int vCorrectOrWrong(string UserAnswer, string CorrectAnswer, int k);
string vAnswerSheet(string sArray[], string sUserAnswer, int iElement);
void vResults(int,int);

int main()
{
const int ctSIZE = 5;
string sQuestions[ctSIZE] = {"1. What was the first planet to be discovered by the telescope?", "2. What is the diameter of earth?",
                             "3. Name the yellow teletubby?", "4. In which state was the first oil well drilled in the Untied States?", "5. How many tentacles does a squid have?" };
string sLetterAnwers[ctSIZE] = {"a. Mars b. Mercury c. Uranus d. Jupiter", "a. 5,000 miles b. 6,000 miles c. 7,000 miles d. 8,000 miles",
                                "a. Dipsy b. Po c. LaLa d. Tinky Winky", "a. Pennsylvania b. Texas c. Wyoming d. North Dakota", "a. 8 b. 9 c. 10 d. 11"};
string sUserAnswer;
string a;
int i = 0;
int j = 0;
int k =0;

while(i != 5)
{
cout << sQuestions[i] << endl;
cout << sLetterAnwers[i] << endl;
cin >> sUserAnswer;

a = vAnswerSheet(sLetterAnwers,sUserAnswer,i);
j = vCorrectOrWrong(sUserAnswer, a,k);
i++;
}
vResults(j,ctSIZE);
cout << "PROGRAM ENDED!" << endl;
return 0;
}

string vAnswerSheet(string sArray[], string sUserAnswer, int i)
{
string x = sArray[i];
string Answer;
if(sArray[0] == x)
    Answer = "c";
    else if(sArray[1] == x)
        Answer = "d";
    else if(sArray[2] == x)
        Answer = "c";
    else if (sArray[3] == x)
        Answer = "a";
    else if (sArray[4] == x)
        Answer = "c";

return Answer;
}

为什么 k 不增加提前谢谢!如果代码在编码界看起来很草率,我深表歉意。

 int vCorrectOrWrong(string UserAnswer,string CorrectAnswer, int k)
 {
 if( UserAnswer != CorrectAnswer )
     cout << "WRONG!" << endl;
     else
     {
         cout <<"RIGHT!"<< endl;
         k++;
     }
    return k;
  }

////////////////////////////

 void vResults(int y, int x)
 {
     cout << " You got: " << y << " of the " << x << " Questions correct!"<<       endl;
     y = y*100/x;
     cout <<y<<"%"<< endl;
 }

【问题讨论】:

  • 我建议您阅读您最喜欢的 C++ 教科书中关于按值传递参数与按引用传递参数的内容。

标签: c++ increment


【解决方案1】:

您可以通过引用 vResults 来传递值 k,这样您就不必将相同的值返回到 j 并使用它。像这样-

你的函数 vCorrectOrWrong 看起来像 -

int vCorrectOrWrong(string UserAnswer, string CorrectAnswer, int &k) {..}

而不是将其称为 -

j = vCorrectOrWrong(sUserAnswer, a,k);
..
..
vResults(j,ctSIZE);

这样称呼它-

vCorrectOrWrong(sUserAnswer, a,k);
..
..
vResults(k,ctSIZE);

【讨论】:

  • 嘿,linuxmonk!感谢您的快速回复!你的代码完成了这项工作,就像一个魅力。谢谢你!
【解决方案2】:

您需要更好地跟踪变量。

while (i != 5) 循环中,您不断将j 设置为vCorrectOrWrong 的输出。问题是您总是将k 用作vCorrectOrWrong 的参数,而k 在用作参数时始终等于0j 如果用户最后一个问题答错,则您在输出中使用的末尾为 0,如果用户最后一个问题答对,则为 1。

我强烈建议您使用调试器或在代码中插入cout 语句,以帮助您跟踪变量中存储的值。这个问题由你来解决。

【讨论】:

    猜你喜欢
    • 2021-04-13
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 2019-12-16
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多