从float转换为int

时间:2013-03-20 02:34:06

标签: c++ casting floating-point integer

#include <iostream>
using namespace std;

int main(){
 float const PI = 3.1415926;

int radius = 4;
int peri = 0;
int area = 0;

peri =(float) (PI * 2)* radius;
area = (float) PI * (radius * radius);

cout << "Radius is " << radius << endl;
cout << "Perimeter is " << peri << endl;
cout << "Area is " << area << endl;

return 0;
};

peri和area不会转换为float并始终收到警告“从float转换为int”似乎是个问题..

1 个答案:

答案 0 :(得分:1)

如果你真的想要将peri和area截断为整数,你应该明确地这样做:

peri=static_cast<int>(2*PI*radius);
area=static_cast<int>(PI*radius*radius);

否则,您将收到警告,对于阅读您的代码的任何人来说,这似乎都是错误的。