尝试将数字的整数和小数部分变为两个变量。我尝试了什么:
#include <iostream>
int main(){
float n,m; int k; std::cin >> n;
k = n;
m = n - k;
尝试将浮点数转换为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
减去两个浮点数会返回一个不正确的值,搜索到这个但是答案是高水平的,我无法理解。
我的实际代码:
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或类似的东西,正如我上面评论的那样,代码应该已经停止了,我和#39;我真的要做的是比较浮点数和int数,if(float&gt; 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;
}
答案 0 :(得分:3)
这应该可以解决问题。
int main(){
float n; std::cin >> n;
float whole = floor(n);
float decimal = n - whole;
std::cout << whole << "\n";
std::cout << decimal << "\n";
std::cin.get();
return 0;
}
答案 1 :(得分:3)
为什么不使用专为此目的设计的std::modf
:
float n = 12.34;
float whole, fractional;
fractional = std::modf(n, &whole);
值的非小数部分位于whole
,而小数部分位于fractional
。
如果您想获得整个部分的整数值(请记住,您可以通过这种方式丢失数据,因为float
的范围可能大于{{1}的范围}} ),你可以这样做:
int