C++float変換int
1728 ワード
デフォルトC++floatが従来の
上記の出力結果は次のとおりです.
上記の出力結果は次のとおりです.
int
に変換されたのは、小数点を直接除去した後の数字です.float
はint
に変換する:例えば:9.34 = (int) 9;9.99 = (int) 9
#include
int main()
{
float i = 9.34;
float j = 9.99;
int a, b;
a = (int) i;
b = (int) j;
printf("a = %d
",a);
printf("b = %d
",b);
}
上記の出力結果は次のとおりです.
a = 9
b = 9
float
をint
に変換するには四捨五入して精度を高める必要があるが、基本アルゴリズムは以下の通りである:計算は特に正負数に注意しなければならない問題であり、またround()
関数変換後は数値小数点以下はゼロになるが、この場合はfloat
であり、int
に変換する必要がある.#include
int main()
{
float zer = 0;
float i = 9.34;
float j = 9.99;
float k = -9.34;
float m = -9.99;
int a, b, c, d, e;
int a1, b1, c1, d1, e1;
a = (int) (i * 10 + 5) / 10;
b = (int) (j * 10 + 5) / 10;
c = (int) (k * 10 - 5) / 10;
d = (int) (m * 10 - 5) / 10;
e = zer;
a1 = (int) round(i)
b1 = (int) round(j);
c1 = (int) round(k);
d1 = (int) round(m);
e1 = (int) round(zer);
printf("a = %d
",a);
printf("b = %d
",b);
printf("c = %d
",c);
printf("d = %d
",d);
printf("e = %d
",e);
printf("round a1 is %f
", a1);
printf("round b1 is %f
", b1);
printf("round c1 is %f
", c1);
printf("round d1 is %f
", d1);
printf("round e1 is %f
", e1);
}
上記の出力結果は次のとおりです.
a = 9
b = 10
c = -9
d = -10
e = 0
round a1 is 9
round b1 is 10
round c1 is -9
round d1 is -10
round e1 is 0