gpt4 book ai didi

c - 输入的值未写入数组

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:01 24 4
gpt4 key购买 nike

我正在研究一个我认为会很简单的程序,以尝试让自己熟悉 C 风格的代码(相对于我习惯的 C++),但遇到了障碍。

我已经使用 calloc 为数组分配了内存,并希望用户只需输入一个数字,然后将该数字放入数组中(重复此操作直到数组完全填充)。数组似乎已经创建,但我的代码没有写入数组。该程序在运行时接受输入,将该输入存储到临时变量 q(用于调试目的),但不会将该临时变量的值写入数组。

这是我认为可以解决我的问题的一段代码:

//e is the size of array as indicated by user
values = (double *)calloc(e , sizeof(double));
double q = 0; // holds input just to make sure it works
for (int i = 0; i < e; i++)
{
printf("Please enter value %d: ",i+1);
scanf("%d", &q);
printf("%d", q); // confirms q = "input"
values[i] = q; //This isn't happening for me
}

如果有人能更正(最好是解释)我关于为什么 values[i] 永远不等于 q 的错误,我将不胜感激。

最佳答案

%d 格式说明符用于 int。对于 double use %lf with scanf and %f or %lf with printf .

scanf("%lf", &q);
printf("%f", q); // confirms q = "input"

关于c - 输入的值未写入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17636753/

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