试着把一个数字的整数和小数部分变成两个变量。我尝试过的:
#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左右,就像我上面评论的那样,代码应该已经停止了,我真正想做的是比较浮点数和整型数,如果(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;
}
发布于 2017-12-16 02:29:12
为什么不使用std::modf
,它就是为此而设计的:
float n = 12.34;
float whole, fractional;
fractional = std::modf(n, &whole);
值的非小数部分为whole
,而小数部分为fractional
。
如果您想要获取整个部分的整数值(请记住,由于float
int
),的范围可能大于的范围,因此您可能会以这种方式丢失数据),您只需执行以下操作:
int integralWhole = static_cast<int>(whole);
发布于 2017-12-16 02:25:44
好的,这应该能起到作用。
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;
}
https://stackoverflow.com/questions/47837838
复制相似问题