C++的一点使用经验

    技术2022-05-11  96

    我在使用C++时有一些体会,相信大家都会的。我写出来也是和大家分享一下 1。在C++中数据类型float和double.      同类型为float的变量相比,类型为double的变量可保存的值较大且较为准确,因此我比较喜欢使用double而不是float.这里有一个重要的点要说一下:比如我们定义两个变量      int sum = 1230;      int score = 230;      double avrg  = 0.0f;      如果我们用:      avrg = sum/score;      其中(sum/score)这个计算结果是一个整型, 因为sum和score都是整型。在这样的计算中。小数部分会     丢失,因此C++提供了一元强制类型转换      avrg = static_cast< double > ( sum ) / score;     static_cast < double > (), 这位sum创建了一个临时性的浮点数副本,这就是我们说的显式转换。对比显式转换,当然就是隐式转换,例如当score 被提升为double后,开始执行浮点除法运算。     然后我们输出     cout << "aver is " << setprecision(2)             <<setiosflags( ios::fixedm ios::showpoint )             << avrg <<endl;    setprecision(2) 是被称作参数化操作元的东西,要加一条预编译指令    #include <iomanip>    endl是一个非参数化操纵元,它不需要<iomanip>头文件,如果未指定精度,浮点值会采用6个精度(默认)输出。    注意不要愚蠢的想比较两个浮点数是否相等,应该测试两个浮点数的差值的绝对值是否小于一个指定的小值。这一点在游戏的坐标跟踪中常被用到。 # include <iostream> using std::cout; using std::cin; using std::endl; using std::ios; # include <iomanip> using std::setprecision; using std::setiosflags; int main() {     int score = 0;     int sum = 0;     int count = 0;     double avrg;     cout<<"enter score - to end: ";     cin>>score;     while ( score != -1 )     {         sum = sum + score;         count = count + 1;         cout<< "enter score , -1 to end : ";         cin>>score;     }     if( count != 0 )     {         avrg = static_cast< double > (sum ) / count;         cout << "avrg is " << setprecision(2)             << setiosflags(ios::fixed | ios::showpoint )             << avrg << endl;     }     else     {    cout << " NO!!!!!";     }     return 0; } enter score - to end: 75 enter score , -1 to end : 93 enter score , -1 to end : 23 enter score , -1 to end : 98 enter score , -1 to end : 43 enter score , -1 to end : 54 enter score , -1 to end : 56 enter score , -1 to end : 2334 enter score , -1 to end : 45 enter score , -1 to end : 43 enter score , -1 to end : 454 enter score , -1 to end : 232 enter score , -1 to end : -1 avrg is 295.83  

    最新回复(0)