NekoC

猫でもわかるC言語の個人的なまとめ資料

View on GitHub

03_変数とデータ型

変数について

データ型について

整数型

浮動小数点型

文字型

変数の値の表示

サンプルコード


/*format.c*/

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

int main()
{
	double a = 0.5, b = 10.5;
	int c = 215, d;
	char e = 'A';

	printf("%f + %f =%f\n", a, b, a + b);
	d = c + 11;
	printf("c is %d, and add 11 then %d\n", c, d);
	printf("e is %c\n", e);
	system("pause");

	return 0;

}

出力結果


0.500000 + 10.500000 =11.000000
c is 215, and add 11 then 226
e is A
続行するには何かキーを押してください . . .

書式指定フィールド

フィールド 指定値 意味
flags - 変換される引数を左詰めにする。
flags + 符号をつける。
flags 0 0パディングする。
width 数値 文字幅を指定する。
precision 数値 精度(小数点以下の桁数)を指定する。
typeのプレフィックス h short intに適応させる。
typeのプレフィックス l long修飾
typeのプレフィックス L long double修飾
type d,i 10進整数を指定する。
type o 符号なしの8進数を指定する。
type u 符号なしの10進数を指定する。
type x 符号なしの16進数を指定する。\n a,b,c,d,e,fを利用する。
type X 符号なしの16進数を指定する。\n A,B,C,D,E,Fを利用する。
type f 浮動小数点を指定する。
type e,E 指数変換を指定する。\n ±〇.〇〇e〇〇, ±〇.〇〇E〇〇
type c 文字変換を指定する。
type s 文字列変換を指定する。
type p ポインタ変換を指定する。

サンプルコード


/*format2.c*/

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

int main(){

	double pai = 3.14159265358979;
	int mon = 2;
	float flt = 1.2f;

	/*浮動小数点*/
	printf("%5.2hf\n", flt);
	printf("%-5.2hf\n", flt);
	printf("%05.2hf\n", flt);
	printf("%+08.2hf\n", flt);
	printf("%-08.2f\n", flt);

	/*整数*/
	printf("%d\n", mon = 3);
	printf("%05d\n", mon);

	/*円周率*/
	printf("%e\n", pai);
	printf("%08.2f\n", pai);
	printf("円周率は%fです\n", pai);
	printf("円周率は%1fです\n", pai);
	printf("もう少し詳しい値は%10.81fです\n", pai);
	printf("もう少し詳しい値は%15.131fです\n", pai);
	printf("もう少し詳しい値は%20.18fです\n", pai);
	printf("円周率は%010.2f\n", pai);
	printf("円周率は%-10.2f\n", pai);
	printf("円周率は%10.2f\n", pai);
	system("pause");

	return 0;
}

出力


 1.20
1.20
01.20
+0001.20
1.20
3
00003
3.141593e+000
00003.14
円周率は3.141593です
円周率は3.141593です
もう少し詳しい値は3.141592653589790000000000000000000000000000000000000000000000000000000000000000000です
もう少し詳しい値は3.14159265358979000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000です
もう少し詳しい値は3.141592653589790000です
円周率は0000003.14
円周率は3.14
円周率は      3.14
続行するには何かキーを押してください . . .

以上