我的代码问题我需要制作。我必须从命令行中获取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是比较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;
}
答案 0 :(得分:0)
搜索匹配项并显示结果是两项独立的任务。不尝试同时进行操作更简单,更灵活。
首先搜索匹配并将它们存储在数组中。然后根据需要显示数组的内容。
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;
}
许多简单的程序应遵循以下结构:
答案 1 :(得分:-1)
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
count = count + 1;
}
}
printf("%d are the same: ", count);
for(b=0; b < 7; b++) {
if (lottoNumbers[a] == winningNumbers[b]) {
printf(" %d", winningNumbers[b]);
}
}
printf("\n");
答案 2 :(得分:-1)
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]);