( C/C++ の場合) #include <stdlib.h> double strtod(const char *str, char **stop) str : 変換される文字列 stop : 変換の終了位置を示すポインタを受け取るメモリへのポインタ ( Java の場合: Double クラスの static メソッド) double parseDouble(String str)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *s,*stop;
double x;
long l;
unsigned long u;
s = " -2309.12e-15double"; /* doubleへの変換 */
x = strtod(s, &stop);
printf("文字列=%s 数値=%e\n", s, x);
printf(" 変換停止位置=%s\n", stop);
s = " 1101long"; /* long intへの変換 */
l = strtol(s, &stop, 2);
printf("文字列=%s 数値=%ld\n", s, l);
printf(" 変換停止位置=%s\n", stop);
s = " 1234567890unsigned long"; /* unsigned longへの変換 */
u = strtoul(s, &stop, 10);
printf("文字列=%s 数値=%ld\n", s, u);
printf(" 変換停止位置=%s\n", stop);
return 0;
}
(出力)
文字列= -2309.12e-15double 数値=-2.309120e-12
変換停止位置=double
文字列= 1101long 数値=13
変換停止位置=long
文字列= 1234567890unsigned long 数値=1234567890
変換停止位置=unsigned long
import java.io.*;
public class Test {
public static void main(String args[])
{
String s;
double x;
int i;
long l;
s = "-2309.12e-15"; /* doubleへの変換 */
x = Double.parseDouble(s);
System.out.println("文字列=" + s + " 数値(double)=" + x);
s = "6.775"; /* doubleへの変換 */
x = Double.parseDouble(s);
System.out.println("文字列=" + s + " 数値(double)=" + x);
s = "-12345"; /* intへの変換 */
i = Integer.parseInt(s);
System.out.println("文字列=" + s + " 数値(int)=" + i);
s = "1234567890"; /* long intへの変換 */
l = Long.parseLong(s);
System.out.println("文字列=" + s + " 数値(long)=" + l);
}
}
(出力)
文字列=-2309.12e-15 数値(double)=-2.30912E-12
文字列=6.775 数値(double)=6.775
文字列=-12345 数値(int)=-12345
文字列=1234567890 数値(long)=1234567890
| ホームページ | 目次 | 演習解答例目次 | 付録目次 | 索引 |