2

有人可以帮我(对不起英语),我试图将字符串转换为双精度,但是当我无法得到它时,这是我的代码(谢谢,我将非常感谢帮助):

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

#define MAX_LONG 5

char bx[MAX_LONG];
double cali=0;

int main() {
scanf("%c",bx);
cali = strtod(bx,NULL);
printf("%f",cali);
return 0;
}

当我在输出中输入大于 10 的值时,它只打印第一个数字,如下所示:

 input: 23
 output: 2.00000
 input: 564
 output: 5.00000
4

2 回答 2

2

您使用的scanf()说明符错误,除非您指定多个字符,否则数组不会nul终止,我建议如下

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

int main() 
{
    char   bx[6]; /* if you want 5 characters, need an array of 6
                   * because a string needs a `nul' terminator byte
                   */
    double cali;
    char  *endptr;

    if (scanf("%5s", bx) != 1)
    {
        fprintf(stderr, "`scanf()' unexpected error.\n");
        return -1;
    }

    cali = strtod(bx, &endptr);
    if (*endptr != '\0')
    {
        fprintf(stderr, "cannot convert, `%s' to `double'\n", bx);
        return -1;
    }        
    printf("%f\n", cali);
    return 0;
}
于 2015-04-24T23:13:22.430 回答
0

您应该尝试此更改以使其正常工作。

第一:改变

scanf("%c",bx); /*Here you're reading a single char*/

对此:

scanf("%s",bx);/*Now you're reading a full string (No spaces)*/

第二:改变

cali = strtod(bx,NULL);

对此:

cali = atof(bx);

我认为这对你来说是完美的。

于 2015-04-25T01:14:38.960 回答