简体   繁体   English

如何将单字符转换为双字符

[英]How to convert single char to double

I try to create a program that can evaluate simple math expression like "4+4".我尝试创建一个可以评估简单数学表达式(如“4+4”)的程序。 The expression is given from the user.该表达式由用户给出。

The program saves it in a char* and then searches for binary operation (+,-,*,:) and does the operation.程序将其保存在一个char* ,然后搜索二进制操作 (+,-,*,:) 并执行操作。

The problem is that I can't figure out how to convert the single char into a double value.问题是我不知道如何将单个char转换为double值。

I know there is the atof function but I want to convert single char .我知道有atof函数,但我想转换单个char

There is a way to do that without creating a char* ?有没有办法在不创建char*情况下做到这一点?

A char usually represents a character.一个char通常代表一个字符。 However, a single char is simply an integer in range of at least [-127,+127] (signed version) or at least [0,255] (unsigned version).但是,单个char只是一个范围至少为 [-127,+127](有符号版本)或至少为 [0,255](无符号版本)的整数。

If you obtained a character looking as a digit, the value stored in it is an ASCII number representing it.如果您获得一个看起来像数字的字符,则存储在其中的值是一个代表它的 ASCII 数字。 Digits start at code 48 (for zero) and go up incrementally till code 57 (for nine).数字从代码 48(零)开始并逐渐增加,直到代码 57(九)。 Thus, if you take the code and subtract 48, you get the integer value.因此,如果您将代码减去 48,您将得到整数值。 From there, converting it to double is a matter of casting.从那里,将其转换为 double 是一个铸造问题。

Thus:因此:

char digit = ...
double value = double(digit - 48);

or even better, for convenience:甚至更好,为方便起见:

char digit = ...
double value = double(digit - '0'); //'0' has a built-in value 48

There is a way to do that without creating a char* ???有一种方法可以在不创建 char* 的情况下做到这一点?

Sure.当然。 You can extract the digit number from a single char as follows:您可以从单个char提取数字,如下所示:

char c = '4';
double d = c - '0'; 
        // ^^^^^^^ this expression results in a numeric value that can be converted
        //         to double

This uses the circumstance that certain character tables like ASCII or EBCDIC encode the digits in a continuous set of values starting at '0' .这使用了某些字符表(如ASCIIEBCDIC)对从'0'开始的一组连续值中的数字进行编码的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM