扫描的第二个值未更改

  • 本文关键字:第二个 扫描 c
  • 更新时间 :
  • 英文 :


&添加到y时,y永远不会改变,但是如果我删除&y会发生变化,但程序在scanf后立即结束:

double scan_data(char *a, double *b) {
char x;
double y;
int result;
printf("input en operator og hvis relevant, operand: ");
scanf("%c, %lf", &x, &y);
/* Hvis unær output=0,0. */
printf("scan y step 1: %lf", &y);
unary(x, &result);
if (result == -1) {
y = 0.0;
}
*a = x;
*b = y;
printf("scan b: %d", *b);
return 0;
}

scanf()的参数必须是scanf()存储转换值的地址。如果y被定义为double,则必须为需要指向double的指针的转换%lf传递&y(y的地址)。

对于printf,您必须为%f(或忽略l%lf)传递一个double值。通过&y是一个错误,只是通过y.

最终printf也存在类型不匹配:inprintf("scan b: %d", *b);%d需要一个int值,但*b具有类型double。你应该写:

printf("scan b: %fn", *b);

以下是修改后的代码:

double scan_data(char *a, double *b) {
char x;
double y;
int result;
printf("input en operator og hvis relevant, operand: ");
if (scanf("%c, %lf", &x, &y) != 2) {
printf("invalid inputn");
return -1.0;
}
/* Hvis unær output=0,0. */
printf("scan y step 1: %fn", y);
unary(x, &result);  // no info on this function?
if (result == -1) {
y = 0.0;
}
*a = x;
*b = y;
printf("scan b: %fn", *b);
return 0.0;
}
printf("scan y step 1: %lf", &y);

调用未定义的行为,因为具有错误类型的数据被传递给printf()%lf期望double&y具有类型double*

它应该是

printf("scan y step 1: %f", y);

您应该删除额外的&。此外,%f也应该用于打印doubleprintf()。(%lf在C99或更高版本中还不错)

printf("scan b: %d", *b);

还会调用未定义的行为,因为double会传递到预期int的位置。

它应该像

printf("scan b: %f", *b);

printf("scan b: %d", (int)*b);

最新更新