为什么打印不正确?

Why isn't it printing properly?

本文关键字:不正确 打印 为什么      更新时间:2023-10-16
#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;
 }

您可以通过引用 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);

您需要更好地跟踪变量。

while (i != 5)循环中,您不断将j设置为vCorrectOrWrong输出的任何输出。 问题是您始终使用 k 作为参数进行vCorrectOrWrong,并且当k用作参数时,它始终等于 0。 如果用户弄错了最后一个问题,则在输出中使用的末尾的j将为 0,如果用户正确回答了最后一个问题,则为 1。

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