gpt4 book ai didi

c - C 代码结果不正确

转载 作者:行者123 更新时间:2023-11-30 21:43:28 24 4
gpt4 key购买 nike

我有这个代码

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

main()
{
double b;int a[2],*c;
void myfunction();
c=(int*)(malloc(1));
b=10.;
*c=5;
a[1]=1;a[2]=2;

printf("before call %f $d $d %d\n",b,a[1],a[2],*c);
printf("before call %f $d $d %d\n",b,a[1],a[2],*c);
myfunction(b,a,c);
printf("after call %f $d $d %d\n",b,a[1],a[2],*c);
}

void myfunction(x,y,d)
double x;int y[2],*d;
{
double z;
x=2*x;
y[1]=3*y[1];
y[2]=3*y[2];
*d =*d+2;
}

当我执行它时,我收到了这个

before call 10.000000 $d $d 1
before call 10.000000 $d $d 1
after call 10.000000 $d $d 3

我希望在第一次和第二次通话中得到 5 个,在最后一次通话中得到 7 个a[i] 未显示。你能告诉我为什么吗?谢谢

最佳答案

你的代码应该是什么样子

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void myfunction(double x, int y[2], int *d);

int main(int argc, char **argv)
{
int a[2];
int *c = malloc(sizeof(int));
double b=10.0;
*c = 5;
a[0]=1;
a[1]=2;

printf("before call %f %d %d %d\n",b,a[0],a[1],*c);
myfunction(b,a,c);
printf("after call %f %d %d %d\n",b,a[0],a[1],*c);
}

void myfunction(double x, int y[2], int *d)
{
double z;
x=2*x;
y[0]=3*y[0];
y[1]=3*y[1];
*d =*d+2;
}

注意,malloc 正确的大小

数组从0开始

现代函数声明

在首次使用时声明变量。

固定 printf 格式(% 不是 $)

关于c - C 代码结果不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43897400/

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