中断并继续 (C)

Break and Continue (C)

"Simon Says" is a memory game where "Simon" outputs a sequence of 10 characters (R, G, B, Y) and the user must repeat the sequence. Create a for loop that compares the two strings starting from index 0. For each match, add one point to userScore. Upon a mismatch, exit the loop using a break statement.

Ex: The following patterns yield a userScore of 4:

simonPattern: R, R, G, B, R, Y, Y, B, G, Y

userPattern: R, R, G, B, B, R, Y, B, G, Y

#include <stdio.h>
#include <string.h>

int main(void) {
   char simonPattern[50] = "";
   char userPattern[50] = "";
   int userScore = 0;
   int i = 0;

   userScore = 0;
   strcpy(simonPattern, "RRGBRYYBGY");
   strcpy(userPattern, "RRGBBRYBGY");

   while (userPattern[i] = simonPattern[i]) {
      userScore = userScore + 1;
      ++i;
      if (userPattern[i] != simonPattern[i]) {
         break;
      }
   }

   printf("userScore: %d\n", userScore);

   return 0;
}

我尝试了 运行 代码,但我得到了这个

http://i.imgur.com/T7srTbb.png

有谁知道是什么导致了额外的 1?

谢谢。

更改 while 循环中的条件以使用 == 而不是 =。现在你正在做一个赋值而不是比较这两个意味着第一个字符总是相同的并且得分为 1。然后你可以从循环内部删除 if 语句。

作业要求您使用 for 循环而不是 while。如果您只是将 I 移入 for 循环并填写其余部分,同时将增量移动到 != 之后,检查它是否有效。

while (simonPattern.at(i) == userPattern.at(i))
{
++i;
++userScore;
}

请务必使用 "FOR" 循环,我看到您使用的是 "WHILE" 循环。您需要使用 == 比较运算符而不是 = 赋值运算符。

这是我的代码,运行良好:

#include <stdio.h>
#include <string.h>

int main(void) {
   char simonPattern[50];
   char userPattern[50];
   int userScore;
   int i;

   userScore = 0;
   strcpy(simonPattern, "RRGBRYYBGY");
   strcpy(userPattern, "RRGBBRYBGY");

   i = 0;

   for ( i = 0; userPattern[i] == simonPattern[i]; ++i) {
      userScore = userScore +1;
      if (userPattern[i] != simonPattern[i]){
         break;
      }
   }


   printf("userScore: %d\n", userScore);

   return 0;
}

看到一堆答案后,运行 在我的 WGU ZyBooks 课程中遇到了同样的问题,它与 Potato 的答案非常相似,只是我在使用他的代码时遇到错误,因为 userPattern 是String 类型和 int 类型的 i 不起作用。在字符串后的.charAt(i)中添加并修复了问题。

for (i = 0; userPattern.charAt(i) == simonPattern.charAt(i); ++i) {
    userScore = userScore +1;
    if (userPattern.charAt(i) != simonPattern.charAt(i)){
    break;
   }
}