0

编程新手,我正在循环一个后缀字符串并尝试单独检索数字,我一次只需要一个。

最初我为整数编写了这个并且只是做了“-'0'”,但是,我现在需要尝试使它与十进制数兼容。

下面是我的整数转换示例,我该如何调整?

int i;
char postfix[] = "4 3 +";

for (i=0; i<strlen(postfix); i++) {
    if (isalnum(postfix[i])) {
        int value=(postfix[i]-'0');
        printf("%d\n", value);
    }
}

4
3

例如如何评估何时

char postfix[] = "1.2 3.4 +"

将值存储为双精度

4

2 回答 2

0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{

    int i;
    double res;
    char *ptr1;
    char *ptr2;
    char postfix[] = "4.5 3.4 4.5 7.6 8.9 3.6 +";

    ptr1 = postfix;
    res = strtod(ptr1, &ptr2);
    
    
    while (res!= 0.0f )  // strtod() return 0.0 if double value is not found.
    {
        printf("Value in decimal is %lf\n",res);
        ptr1 = ptr2;
        res = strtod(ptr1, &ptr2);
    }
    return 0;
}

输出是:

Value in decimal is 4.500000
Value in decimal is 3.400000
Value in decimal is 4.500000
Value in decimal is 7.600000
Value in decimal is 8.900000
Value in decimal is 3.600000

请参阅此链接以了解strtod() functionhttps ://linux.die.net/man/3/strtod

于 2020-11-18T06:54:35.673 回答
0

用于strtod()解析字符串以获得有效的double.

current == endptr表示转换失败。

char postfix[] = "4 3 +";
char *current = postfix;
char *endptr;

double v1 = strtod(current, &endptr);
if (current == endptr) TBD_code_handle_failure();
else current = endptr; 

double v2 = strtod(current, &endptr);
if (current == endptr) TBD_code_handle_failure();
else current = endptr; 

while (isspace((unsigned char) *current)) {  // skip white-space
  current++;
}

if (strchr("+-*/", *current) == NULL) {
  TBD_code_handle_failure(); // unexpected operator
}

printf("%g %g %c\n", v1, v2, *current);

或者 ....

double v1, v2;
char oper;
if (sscanf(postfix, "%lf %lf %c", &v1, &v2, &oper) == 3) {
  ; // Success!
}
于 2020-11-19T11:59:23.703 回答