( C/C++ の場合) #include <stdlib.h> int atoi(const char *str) str : 変換される文字列 ( Java の場合: Integer クラスの static メソッド) int parseInt(String str)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *s;
double x;
int i;
long l;
s = "-2309.12e-15"; /* doubleへの変換 */
x = atof(s);
printf("文字列=%s 数値(double)=%e\n", s, x);
s = "6.775"; /* doubleへの変換 */
x = atof(s);
printf("文字列=%s 数値(double)=%f\n", s, x);
s = "-12345"; /* intへの変換 */
i = atoi(s);
printf("文字列=%s 数値(int)=%d\n", s, i);
s = "1234567890"; /* long intへの変換 */
l = atol(s);
printf("文字列=%s 数値(long)=%ld\n", s, l);
return 0;
}
(出力)
文字列=-2309.12e-15 数値(double)=-2.309120e-12
文字列=6.775 数値(double)=6.775000
文字列=-12345 数値(int)=-12345
文字列=1234567890 数値(long)=1234567890
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
| ホームページ | 目次 | 演習解答例目次 | 付録目次 | 索引 |