简体   繁体   English

分割两位数字

[英]Split two digit numbers

I try to split any number of two digits and get result in two different variables. 我尝试将任意数量的两位数分割,并得到两个不同变量的结果。 I had a problem with a specific number: 23 . 我对以下特定数字有疑问: 23

int root = 23;
float div = (float)root/10.0; // div = 23.0/10.0 = 2.3

int left = (int)div; // left = 2
int right = ((float)div - (float)left) * 10.0; // right = (2.3 - 2) * 10.0 = 0.3 * 10.0 = 3

printf("%d", right); // 2, why ?

There is a lot of float-to-int operations and I got some troubles with the final result. 有很多从浮点到整数的操作,最终结果使我有些麻烦。 Have I miss or didn't catch something ? 我想念或没抓住东西吗?

Since 0.3 may not be represented exactly in binary, you end up with 2.9999… that became 2 when converted to an int . 由于0.3可能无法精确地用二进制表示,因此您最终得到2.9999…转换为int时变为2

Instead: 代替:

int root = 23;
int left = root / 10;
int right = root % 10;

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

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