数组
同种类型的多个数据
[]
定义数组 --->直接或间接知道数组的个数
int a[3] = {}
int a[] = {1,2}
int a[4] = {1,2,3}//补上0
Demo
1.产生四个随机数 (4个 不重复 1-9 从小到大)
2.提示用户输入 1 2 3 4
3.比较
正确 - 结束
不正确 - 继续2-3 2-3
1、
#include
#include
#include
#include
int main() {
int org[4] = {};
srand(time(0));
for (int i =0; i <4; ++i) {
int temp = rand()%9+1;
org[i] = temp;
printf("%d",temp);
if (i ==0){
org[0] = temp;
continue;
}else{
bool exists =false;
for (int j =0; j < i; ++j) {
if (org[j] == temp){
exists =true;
break;
}
}
if (exists ==true){
i--;
}else{
org[i] = temp;
for (int j = i-1; j >=0; --j) {
if (temp < org[j]){
org[j+1] = org[j];
org[j] = temp;
}else{
break;
}
}
}
}
}
printf("\n");
for (int i =0; i <4; ++i) {
printf("%d",org[i]);
}
int guess[4] = {};
int aCount =0;
int bCount =0;
while (1) {
printf("\n请输入猜测数字:");
for (int i =0; i <4; ++i) {
scanf("%d", &guess[i]);
}
for (int i =0; i <4; ++i) {
int num = org[i];
for (int j =0; j <4; ++j) {
if (num == guess[j]) {
if (i == j) {
aCount++;
}else {
bCount++;
}
break;
}
}
}
if (aCount ==4) {
printf("恭喜你猜对了!\n");
break;
}else{
printf("%dA %B\n",aCount,bCount);
aCount =0;
bCount =0;
}
}
return 0;
}