這個彩票輸入有什么問題 - 抽獎代碼?
我一直在研究一個代碼,當我通過scanf(1~45整數)輸入7個數字時,隨機選擇7個數字,比較2組7個數字(我的和隨機的),程式輸出多少我的號碼與隨機挑選的號碼相同。(數字的順序無關緊要)如果我輸入多個相同的數字,例如 1 1 2 3 4 5 6,或輸入大于 45 的數字,則必須列印錯誤訊息。如果這兩個錯誤都為真,則應該有單獨的錯誤訊息。
這個彩票輸入有什么問題 - 抽獎代碼?
我一直在研究一個代碼,當我通過 scanf(1~45 整數)輸入 7 個數字時,隨機選擇 7 個數字,2
當我運行程式時,隨機選擇數字(抽獎)似乎作業正常,沒有重疊的數字。匹配號碼的計數也有效。奇怪的是錯誤訊息。由于計數有效,我假設輸入值保存得很好,但程式總是輸出多行(7,正好)“你不能選擇相同的數字”。誰能幫我解決這個問題?源代碼如下。
#include <stdio.h>
#include <stdlib.h>
int main () {
int yours[7];
printf("Buy yours: ");
for (int i=0; i<7; i ){
scanf("%d", &yours[i]);
for (int j=0; j<7; j ){
for (int k=0; k<7; k ){
if (yours[j] == yours[k] && yours[k]>45){
printf("You cannot choose same number and number out of range from 1 to 45.");
printf("\n\n");
printf("Buy yours: ");
}
else if (yours[j]>45){
printf("You cannot choose number out of range from 1 to 45.");
printf("\n\n");
printf("Buy yours: ");
break;
}
else if (yours[j] == yours[k]){
printf("You cannot choose same number.");
printf("\n\n");
printf("Buy yours: ");
break;
}
break;
}
break;
}
}
printf("Lottery result: ");
int lottery[7];
for (int i=0; i<7; i ){
lottery[i] = rand() %45 1;
for (int j=0; j<i; j ){
if (lottery[i] == lottery[j]) {
i--;
break;
}
}
}
for (int k=0; k<7; k ){
printf("%d ", lottery[k]);
}
int a = 0;
for (int i=0; i<7; i ){
for (int j=0; j<7; j ){
if (lottery[i] == yours[j]) {
a ;
}
}
}
printf("\n");
printf("The number of yours : %d", a);
return 0;
}
uj5u.com熱心網友回復:
正如其他人已經說過的,代碼是一團糟,因為沒有標識,所以很難理解,而且代碼出錯的風險很高。在這里查看:https
:
//codehs.gitbooks.io/introcs/content/Programming-with-Karel/how-to-indent-your-code.html 您是否使用過類似舊版本的 Dev C 來撰寫代碼? 我看到其他人為此苦苦掙扎。
我還建議您不要將陣列大小指定為數字:例如 int array[7]; 但要以這種方式定義一個常量 int:
#define array_size 7
int array[array_size];
這將使您無需重寫所有代碼即可修改程式,并且還可以防止出現一些錯誤,并且您應該為變數提供自我描述的名稱。
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int yours[7];
printf("Buy yours: ");
for (int i=0; i<7; i )
{
scanf("%d", &yours[i]);
我認為問題就在這里,因為您正在比較仍然不存在的值,如果完全初始化,第二個 for 回圈和第三個回圈在您的陣列之前執行。要修復它,你必須改變他們的條件
for (int j=0; j<7; j )
{
for (int k=0; k<7; k )
{
if (yours[j] == yours[k] && yours[k]>45)
{
printf("You cannot choose same number and number out of range from 1 to 45.");
printf("\n\n");
printf("Buy yours: ");
}
else if (yours[j]>45)
{
printf("You cannot choose number out of range from 1 to 45.");
printf("\n\n");
printf("Buy yours: ");
break;
}
else if (yours[j] == yours[k])
{
printf("You cannot choose same number.");
printf("\n\n");
printf("Buy yours: ");
break;
}
break;
}
break;
}
}
printf("Lottery result: ");
int lottery[7];
for (int i=0; i<7; i )
{
lottery[i] = rand() %45 1;
for (int j=0; j<i; j )
{
if (lottery[i] == lottery[j])
{
i--;
break;
}
}
}
for (int k=0; k<7; k )
{
printf("%d ", lottery[k]);
}
int a = 0; //What does it mean?
for (int i=0; i<7; i ) //Also check these
{
for (int j=0; j<7; j )
{
if (lottery[i] == yours[j])
{
a ;
}
}
}
printf("\n");
printf("The number of yours : %d", a);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530468.html
