//This program is a basic scrabble game with some error checking.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define num_letters 7
#define tiles_max 100
//value 1 and 2 are the same, they were passed from a generate letter set if statement to determine the max
//value of things to add up
int sum_array (int value1, int letter_set[], int value2, int tile_set[]){
int counter2, sum_of_array;
sum_of_array = 0;
for(counter2 = 0; counter2 < value1; counter2++){
sum_of_array += tile_set[counter2] - letter_set[counter2];
}
return sum_of_array;
}
void generate_letter_set (int letter_set[], int size_letter_set, int lettersbgood){
const int tile_set[] = {9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1, 2};
int counter1, counter3, chargen;
srand((unsigned) time(NULL));
for(counter1 = 0; counter1 < lettersbgood; counter1++){
chargen = rand() % (tiles_max - counter1);
for(counter3 = 0; counter3 < 27; counter3++){
if(chargen >= sum_array(counter3, letter_set, counter3, tile_set) && chargen < (sum_array(counter3, letter_set, counter3, tile_set)+(tile_set[counter3]-letter_set[counter3]))){
letter_set[counter3] += 1;
}
}
}
}
int main()
{
int size_letter_set = 27, counter4;
int letter_set[27] = {0};
printf("This program plays a game of scrabble.\n");
generate_letter_set(letter_set, size_letter_set, num_letters);
printf("Your letters are: \n");
for(counter4 = 0; counter4 < size_letter_set; counter4++){
printf("%d ", letter_set[counter4]);
}
return 0;
}
我希望它能打印出最多7个非零字符,最多可添加7个字符,并且至少有1个非零字符,最多可添加7个,其余字符为零。
我得到的是不同数量的非零字符总数超过7。
样本输出:0 0 0 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 1 1 0 0 有时也有2或3。该程序使用c99标准。
我想知道为什么它产生了太多的输入(我认为它经历了太多次循环)。在此先感谢您的帮助。
答案 0 :(得分:0)
主要问题是在模数中使用值为100的tiles_max
来获取[27]数组的索引。这简化了选择。
//This program is a basic scrabble game with some error checking.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_LETTERS 7
#define LETTER_SET 27
void generate_letter_set (int letter_set[], int lettersbgood){
const int tile_set[LETTER_SET] = {9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1, 2};
int counter1, chargen;
counter1 = lettersbgood;
do {
chargen = rand() % (LETTER_SET);
if ( tile_set[chargen] > letter_set[chargen]){
letter_set[chargen] += 1;
counter1--;
printf("%d\n", letter_set[chargen]);
}
} while ( counter1);
}
int main()
{
int counter4;
int letter_set[LETTER_SET] = {0};
srand((unsigned) time(NULL));
printf("This program plays a game of scrabble.\n");
generate_letter_set(letter_set, NUM_LETTERS);
printf("Your letters are: \n");
for(counter4 = 0; counter4 < LETTER_SET; counter4++){
printf("%d ", letter_set[counter4]);
}
printf("\n");
return 0;
}