<分区>
尝试将数字的整数部分和小数部分放入两个变量中。我尝试了什么:
#include <iostream>
int main(){
float n,m; int k; std::cin >> n;
k = n;
m = n - k;
尝试将 float 转换为 int 并收到编译器警告,该数字可能不正确,经过测试,确实不正确,无法获得预期结果。对此进行搜索,除了使用 floor()
之外找不到任何其他解决方法。
我的实际代码:
int main() {
float n; cin >> n;
int nfloor = n;
cout << nfloor << "\n";
float nfloat = n - nfloor; int nfloatfloor;
cout << nfloat << "\n";
do {
nfloat *= 10;
nfloatfloor = nfloat;
cout << nfloat << "\n" << nfloatfloor << "\n";
} while (nfloat > nfloatfloor);
}
结果:
Input: 12.34
Output :
12
0.34
3.4
3
34
34
340
340
3400
3400
34000
34000
340000
340000
3.4e+06
3400001
3.4e+07
34000016
两个 float 相减会返回一个不正确的值,对此进行了搜索,但答案的级别很高,我无法理解。
我的实际代码:
int main() {
float n; cin >> n;
float nfloor = floor(n);
cout << nfloor << "\n";
float nfloat = n - nfloor; float nfloatfloor;
cout << nfloat << "\n";
do {
nfloat *= 10;
nfloatfloor = floor(nfloat);
cout << nfloat << "\n" << nfloatfloor << "\n";
} while (nfloat > nfloatfloor);
}
结果:
Input: 12.34
Output:
12
0.34
3.4
3
34
34 //Run should stop here because of the while loop bit it doesn't, funny thing is it gives me different results sometimes, last time it gave me 35 and 34
340
340
3400
3400
34000
34000
340000
340000
3.4e+06
3.4e+06
3.4e+07
3.4e+07
@Slava 看看这句话上面的输出,编译器打印了 34 和 34,重复的答案显示 couts 是 34.0000000000000004 或类似的东西,正如我在上面评论的那样,代码应该已经停止了,我我真正想做的是比较 float 和整数,如果 (float >int) 代码应该继续,如果不是应该停止,那么有什么解决办法吗? @hnefatl 我试过你的答案,编译器挂起:
int main() {
float n2, whole, fractional, fractional2, whole2; cin >> n2;
int denominator = 1;
fractional = modf(n2, &whole);
do {
fractional *= 10;
fractional2 = modf(fractional, &whole2);
denominator *= 10;
} while (fractional > fractional2);
if (denominator > 1)
denominator /= 10;
cout << denominator;
}