【问题标题】:scanf not saving values correctlyscanf 没有正确保存值
【发布时间】:2019-02-09 17:00:41
【问题描述】:

在我定义的函数中使用 scanf 来更改我通过引用传递给该函数的数组中的值时,它根本不会更改值,同时是双精度类型。

当我从以下位置更改占位符时: scanf("%1f", &x) 到 scanf("%d", &x) 它按预期工作,但我需要为这个项目使用双打。

int main()
{
double varArray[MAX];
zeroFill(varArray);
}


void fill(double *array) {
    for(int i =0; i<MAX; i++){
    printf("what is index %d?\n", i);
    scanf("%f",(array+i));
    printf("%f \n", *(array+i));
}

而不是更改该索引处的值,而是将其更改为 0.000000 或乱码:

 what is index 0?
 1
 0.000000
 what is index 1?
 2
 0.000000
 what is index 2?
 3
 -0.000000
 what is index 3?
 4
 0.000000
 what is index 4?
 5
 0.000000
 what is index 5?
 6
 0.000000
 what is index 6?
 7

182043948477041810000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000 P>

所以对于输入 3 和 7,它返回了一个 -0.000000 和一个很大的 v。 但是这并不一致,因此其他输入会给出类似的输出

【问题讨论】:

  • 请避免数组索引的指针算法。使用例如改为array[i](它完全等于*(array+i))。
  • 是的,就是这样!我试图使用 1 而不是小写 L,因为它们看起来一样大声笑

标签: c printf scanf


【解决方案1】:

要将scanf 的结果写入double,请使用%lf%f 代表float

不要将%ddouble 一起使用。 %d 代表int

(打印时,%lf%f 可用于 floatdouble。这是因为在调用 @987654336 时,float 值会自动提升为 double 值@,或者在调用任何参数对应于参数中...的函数或任何没有原型声明的函数时。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2020-02-01
    • 1970-01-01
    • 2021-11-08
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多