2016-01-09 3 views
0

Я довольно свеж в мире компьютеров и начал работать на c. теперь я строй небольшого проекта о генерации коды (как показано ниже):C | Сравнение между двумя группами массивов

Моего главный: файл

#include <stdio.h> 
#include "connect.h" 
#define EASY 20 
#define NORMAL 15 
#define HARD 10 
#define CRAZY 30 
int main() 
{ 
    int choice = 1; 
    char enter, returnV; 
    system("cls"); 
    printf("Welcome to ""THE MAGSHIMIM CODE BREAKER""!!!\n"); 
    printf("\n"); 
    printf("A secret password was chosen to protect the credit card of Pancratius,\nthe descendant of Antiochus\n"); 
    printf("Your mission is to stop Pancratius by revealing his secret password.\n"); 
    printf("the rules are the follows:\n"); 
    printf("\n"); 
    printf("1. In each round you try to guess the secret password (4 distinct digits)\n"); 
    printf("2. After every guess you'll receive two hints about the password"); 
    printf("\nHITS the number of digits in your guess witch were exactly right.\n"); 
    printf("MISSES the number of digits in your guess witch belong to the password but weremiss-placed\n"); 
    printf("3 - if you'll fail to guess the password after a certain number of rounds \tPancratius will buy all the gift to Hanukkah!!!\n"); 
    printf("\n"); 
    printf("Press Enter to continue...\n"); 
    enter = getch(); 
    if (enter = '\n'){ 
     do{ 
      system("cls"); 
      printf("please choose level:\n"); 
      printf("1 - easy (20 rounds)\n"); 
      printf("2 - normal (15 rounds)\n"); 
      printf("3 - hard (10 rounds)\n"); 
      printf("4 - crazy (random number of rounds 5-25)\n"); 
      printf("Make a choice:"); 
      _flushall(); 
      scanf("%1d",&choice);   
      if (choice == 1 || choice == 2 || choice == 3 || choice == 4){ 
       switch(choice){ 
        case (1): 
         system("cls"); 
         returnV = levels(EASY); 
         break; 
        case (2): 
         system("cls"); 
         returnV = levels(NORMAL); 
         break; 
        case (3): 
         system("cls"); 
         returnV = levels(HARD); 
         break;   
        case (4): 
         system("cls"); 
         returnV = levels(CRAZY); 
         break;   
       switch(returnV){ 
        case('y'): 
         break; 
        case('n'): 
         return 0; 
         break;      
       }  
       } 
      } 
      else if (choice != 1 || choice != 2 || choice != 3 || choice != 4){ 
       system("cls"); 
       printf("please choose level:\n"); 
       printf("1 - easy (20 rounds)\n"); 
       printf("2 - normal (15 rounds)\n"); 
       printf("3 - hard (10 rounds)\n"); 
       printf("4 - crazy (random number of rounds 5-25)\n"); 
       printf("Make a choice:"); 
       _flushall(); 
       scanf("%1d",&choice); 
      } 
     } while (returnV != 'n');   
    } 
    system("PAUSE");   
} 

заголовка для подключения:

char levels (int level); 

"уровни" функция:

#include <stdio.h> 
#include "connect.h" 
#include <time.h> 
#include <stdlib.h> 
char cases (int myCase, char crazyl); 
char levels (int level) {  
    char crazyl = 'n',playerChoice; 
    switch (level){ 
     case (20): 
      playerChoice = cases (level,crazyl); 
      printf ("\n%c\n",playerChoice); 
      return playerChoice; 
      break; 
     case (15): 
      playerChoice = cases (level,crazyl); 
      return playerChoice; 
      break; 
     case (10): 
      playerChoice = cases (level,crazyl); 
      return playerChoice; 
      break; 
     case (30): 
      crazyl = 'x'; 
      level = rand() % (25 - 5 + 1); 
      playerChoice = cases (level,crazyl); 
      return playerChoice; 
    }   
} 

int ranGen (int code1,int code2, int code3, int code4); 
char cases (int level,char crazyl) 
{ 
    unsigned int check; 
    char choise = 't',code1,code2,code3,code4; 
    if(level > 0){ 
     while (level > 0){ 
      if(crazyl == 'n'){ 
      printf("Write your guess (only 1-6, no ENTER is needed) [%d guess left]\n",level); 
      } 
      else if (crazyl == 'x'){ 
      printf("Write your guess (only 1-6, no ENTER is needed) [xxx guess left]\n"); 
      } 

    code1 = getch(); 
    printf("%c",code1); 
    code2 = getch(); 
    printf("\t%c",code2); 
    code3 = getch(); 
    printf("\t%c\t",code3); 
    code4 = getch(); 
    printf("%c\n",code4);  
    if(code1 > '0' && code1 < '7' && code2 > '0' && code2 < '7' && code3 > '0' && code3 < '7' && code4 > '0' && code4 < '7'){ 
     check = ranGen(code1,code2,code3,code4); 
     level--; 
    } else { 
     printf("\nnot a good number only numbers between 1-6\n"); 
     level--; 
    } 
    if (level == 0) { 
     printf("FOR GOD SAKE WE LOST!!!\n"); 
     printf("The secret password was:\n"); 
     while (choise != 'y' || choise != 'n') { 
      if (choise != 'y' || choise != 'n') { 
       printf("keep playing? (y/n):"); 
       _flushall(); 
       scanf("%1c",&choise); 
        if (choise == 'y' || choise == 'n') { 
         return choise; 
        } else { 
         continue; 
        } 
      } 
     } 

    }  
     } 
    } 
} 

int ranGen(int code1,int code2, int code3, int code4) { 
    unsigned int ranCode[3],check,code[3]; 
    code[0] = (int) code1 - 48; 
    code[1] = (int) code2 - 48; 
    code[2] = (int) code3 - 48; 
    code[3] = (int) code4 - 48;  
    do {  
     ranCode[0] = rand() % (6 - 1 + 1); 
     ranCode[1] = rand() % (6 - 1 + 1); 
     ranCode[2] = rand() % (6 - 1 + 1); 
     ranCode[3] = rand() % (6 - 1 + 1); 
    } while (code[0] != ranCode[0] || code[1] != ranCode[1] || code[2] != ranCode[2] || code[3] != ranCode[3]); 
} 

Теперь моя проблема в функции ranGen на палитре «levels».

Мне нужно Генерировать 4 случайных числа между 1-6, которые отличаются друг от друга (1234 - это нормально, 1878 не в порядке, 2234 тоже не нормально) и что пользователь угадает цифры, а если он сделает правильные цифры позволяет сказать:

generated code = 2345 
guess = 1364 

пользователь получит: 1 ВИТ и 1 MISS а если пользователь будет вводить 2222 он получит 1 HIT и 3 промаха.

Теперь я очень потерян здесь, и любая помощь будет большой.

+0

Вы должны выкладываете код прямо здесь. –

+1

Еще лучше, опубликуйте _only_, что необходимо для иллюстрации вашей конкретной проблемы. A _ [*** Short ***, Self Contained, Correct Compilable, Example] (http://sscce.org/) _ не означает, что вы должны публиковать все. – ryyker

+1

Кроме того, ваши критерии HIT/MISS не ясны. Пожалуйста, повторите его недвусмысленным образом. – ryyker

ответ

0

Я вижу проблемы в функции ranGen() ...

у вас есть ...

неподписанных INT ranCode [3], проверьте, код [3];

ranCode [3] дает вам 3 элемента в этом массиве. Элементы массива начинаются с нуля, так что это даст вам ranCode [0], ranCode [1] и ranCode [2]. Если вы хотите использовать ranCode [3] и код [3], то вам нужно изменить приведенную выше строку на ...

unsigned int ranCode [4], check, code [4];

Это дает вам 4 элемента, пронумерованных от 0 до 3 (0, 1, 2 & 3 равно 4 цифрам).

Я также не уверен, что вы пытаетесь сделать с ...

ranCode [0] = рандов()% (6 - 1 + 1);

... в вашей программе он сначала оценит, что находится внутри скобок, так что 6 - 1 = 5, + 1 = 6. Таким образом, по существу эта строка также будет выглядеть как ranCode [0] = rand ()% 6; компилятору и укажет число от 0 до 5. Если вы хотите добавить его к результату, вы можете использовать: ranCode [0] = (rand()% 6) + 1 ;, что сначала сделало бы случайное число , затем добавьте к нему 1-6 (что я предполагаю, что вы хотели сыграть в кости?).

Во всяком случае, вы передаете code4 к несуществующему элементу, вне диапазона и, вероятно, развращении память где-то, что будет иметь неопределенное поведение, возможно, сбой системы, или эффект памяти других переменную и т.д.

Смежные вопросы