C ++不需要5/9并且似乎类型转换 [英] C++ does not take 5/9 and seems to typecast it

查看:105
本文介绍了C ++不需要5/9并且似乎类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么

  float bla =(5/9)*(100  -  32)result in 0 * 100  - > ; 0? 

  float bla = 5 *(100-32)/ 9; 

运行?
他似乎看到5/9作为一个整数,并使其为0 immidiatly,但结果变量是一个浮点数,所以编译器应该知道他可以使用5/9或?



  

> float bla = 5.0f *(100.0f-32.0f)/ 9.0f;

请注意以下简要列表

  5 // int 
5l // long
5.0 // double
5.0f // float
5ul // unsigned long

更全面的整数文字浮点文字 a>



在您的示例中,整个右侧在 int 操作中执行,隐式转换为 float 。到时为时已晚。



请记住,使用正确的文字很重要


Why does

 float bla = ( 5/9 )* (100 - 32) result in 0 * 100 -> 0 ?

and

float bla= 5*(100- 32) / 9;

work out? He seems to see 5/9 as a integer and make it to 0 immidiatly but the result variable is a float so the compiler should know he can work with 5/9 or?

解决方案

Use the correct literals so you get the correct mathematical behavior

float bla = 5.0f * (100.0f - 32.0f) / 9.0f;

Note the following brief list

5      // int
5l     // long
5.0    // double
5.0f   // float
5ul    // unsigned long

A more comprehensive list of integer literals and floating point literals

In your example, the entire right hand side is performed in int operations, then the final result is implicitly converted to float. By then it is too late.

Remember, using the correct literal is important!

这篇关于C ++不需要5/9并且似乎类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆