我需要做的代码有问题。我必须从命令行中获取14个参数,并使用它们来制作彩票号码、中奖号码,然后将这两个参数进行比较。
例如,使用此参数:./a.out 2 30 17 8 6 19 24 7 6 1 2 3 5 4
应该做这样的事情:
Winning numbers: 2 30 17 8 6 19 24
Lottonumbers: 7 6 1 2 3 5 4
2 are the same: 6 2我的代码几乎按照预期工作,但我似乎无法正确地打印:2是相同的。它总是像这样循环:1 are the same: 6 2 are the same: 2。
数字2是比较两个数组时所发现的相同数字的数量。我的问题是,我如何打印它,使它不会重复的文本和适当的数量?我的头似乎不能工作,即使它是如此简单。
#include <stdio.h>
#include <stdlib.h>
int main(int args, char **argv)
{
int i;
int winningNumbers[7];
int lottoNumbers[7];
int j;
int a;
int b;
int winningNumber;
int lottoNumber;
int count = 0;
printf("Winning numbers: ");
for (i=0;i<7; i++) {
winningNumber = atoi(argv[i+1]);
winningNumbers[i] = winningNumber;
printf("%d ", winningNumber);
}
printf("\n");
printf("Lotto numbers:: ");
for (j= 8; j < args; j++) {
lottoNumber = atoi(argv[j]);
lottoNumbers[j-8] = lottoNumber;
printf("%d ", lottoNumber);
}
printf("\n");
for(a = 0; a < 7; a++) {
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
count = count + 1;
printf("%d are the same: %d", count, winningNumbers[b]);
}
}
}
return 0;
}发布于 2016-09-15 06:54:53
搜索匹配和显示结果是两个独立的任务。更简单、更灵活的做法是不要同时尝试。
首先搜索匹配项并将它们存储在数组中。然后,根据需要显示数组的内容。
int main (int argc, char *argv[])
{
int winningNumbers[7];
int lottoNumbers[7];
int commonNumbers[7];
int count = 0;
// fill winningNumbers
// fill lottoNumbers
// NOTE: the following loop assumes that in both arrays
// no number is repeated.
// You should check that this is indeed the case.
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (lottoNumbers[i] == winningNumbers[j]) {
commonNumbers[count] = lottoNumbers[i];
count++;
}
}
}
printf ("%d are the same:", count);
for (int i = 0; i < count; i++) {
printf (" %d", commonNumbers[i]);
}
printf ("\n");
return 0;
}许多简单的程序应该遵循这样的结构:
发布于 2016-09-15 06:53:45
int finalArray[7];
int i;
for(a = 0; a < 7; a++) {
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
finalArray[count] = lottoNumbers[a];
count = count + 1;
}
}
}
printf("%d are same: ", count);
for(i = 0; i < count; i++)
printf("%d ", finalArray[i]);https://stackoverflow.com/questions/39504361
复制相似问题