gpt4 book ai didi

c - 我应该修复什么才能在此代码中创建随机计算?

转载 作者:行者123 更新时间:2023-12-04 04:12:03 25 4
gpt4 key购买 nike

我想修复我的代码以在此处创建随机操作,我应该在此处修复什么?

    #include <stdio.h>

int main()
{
int x,y,z,a;
char o;
while(1)
{
printf("give your three numbers: ");
scanf("%d %d %d",&x,&y,&z);
printf("(%d*%d-%d) what is the correct among following answers? \n 1. %d\n 2. %d\n 3. %d\n ",
x,y,z,x*y-z,x*y*z,x-y*z);
printf("what is answer? \n: ");
scanf("%d",&a);
if(a == 1)
{
printf("you are right!\n");
}
else
{
printf("you are false!\n\n");
}

getchar();
printf("Would you like to exit programm? (y/n) : ");
scanf("%c",&o);
if (o=='Y' || o=='y')
{
break;
}
else if(o=='N' || o=='n')
{
continue;
}
else
{
printf("Wrong input!!!!");
}
return 0;
}
}

我的意思是我想在运行代码时随机尝试更改操作,例如 * + - 并且连同这个问题,答案应该更改......谢谢!

最佳答案

你的问题主要集中在洗牌答案上。通过从几个站点进行研究,我找到了解决方案。这个有点难,多看几次代码就可以搞定

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

void randomize(int arr[], int n) {
srand(time(NULL));
int i;
for(i = n-1; i > 0; i--) {
int j = rand() % (i+1);
swap(&arr[i], &arr[j]);
}
}

int main() {
int x,y,z,a;
int i;
int a1, a2, a3;
int arr[] = {1, 2, 3};
int n = sizeof(arr)/ sizeof(arr[0]);

printf("give your three numbers: ");
scanf("%d %d %d",&x,&y,&z);

a1 = x*y-z;
a2 = x*y*z;
a3 = x-y*z;

printf("Before shuffle = %d %d %d\n\n", a1, a2, a3);

char answers[] = {a1, a2, a3};

printf("(%d*%d-%d)what is the correct among following answers?\n", x, y, z);

randomize (arr, n);
for(i=0; i<n; i++) {
int index = arr[i];
printf("%2d - %d\n", i+1, answers[index]);
}

return 0;
}

这是输出

第一次运行

give your three numbers: 2
2
2
Before shuffle = 2 8 -2

(2*2-2)what is the correct among following answers?
1 - 8
2 - 2
3 - -2

第二次运行

give your three numbers: 2
2
2
Before shuffle = 2 8 -2

(2*2-2)what is the correct among following answers?
1 - -2
2 - 8
3 - 2

您可以多次尝试。每次答案都会被洗牌。这是Source我已经提到了。

关于c - 我应该修复什么才能在此代码中创建随机计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61555959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com