c语言 整数和浮点数_C ++处理整数和浮点数
c语言 整数和浮点数
C ++中的所有数字 ( All About Numbers in C++ )
In C++ there are two types of numbers. Ints and floats. There are also variants of these types that hold bigger numbers, or only unsigned numbers but they are still ints or floats.
在C ++中,有两种类型的数字。 整数和浮点数 。 这些类型也有一些变体,可以容纳更大的数字,或仅保留无符号数字,但它们仍然是整数或浮点数。
An int is a whole number like 47 without a decimal point. You can’t have 4.5 babies or loop 32.9 times. You can have $25.76 if you use a float. So when you create your program, you must decide which type to use.
一个整数是一个像47这样的整数,没有小数点。 您不能生育4.5个婴儿,也不能循环32.9次。 如果使用浮点数,则可以有$ 25.76。 因此,在创建程序时,必须确定要使用的类型。
为什么不只使用浮标呢? ( Why not Just Use Floats? )
This is what some scripting languages do? Because it’s inefficient, floats take up more memory and are generally slower than ints. Also, you cannot easily compare two floats to see if they are equal like you can with ints.
这是某些脚本语言做什么? 由于浮动效率低下,因此浮动占用更多内存,并且通常比整数慢。 而且,您无法像使用int一样轻松地比较两个浮点数以查看它们是否相等。
To manipulate numbers you have to store them in memory. Because the value can be easily changed, it’s called a variable.
要操纵数字,您必须将其存储在内存中。 由于该值可以轻松更改,因此称为变量。
Read more about variables in What is a Variable?
在什么是变量中阅读有关变量的更多信息。
The compiler that reads your program and converts it into machine code needs to know what type it is, i.e. whether it’s an int or a float, so before your program uses a variable, you must declare it.
读取程序并将其转换为机器代码的编译器需要知道它是什么类型,即它是int还是float,因此在程序使用变量之前,必须对其进行声明 。
Here’s an example.
这是一个例子。
int Counter =0;
float BasicSalary;
You’ll notice that the Counter variable is set to 0. This is an optional initialization. It’s a very good practice to initialize variables. If you don’t initialize and then use them in code without having set an initial value, the variable will start with a random value that may ‘break’ your code. The value will be whatever was in memory when the program was loaded.
您会注意到Counter变量设置为0。这是可选的初始化。 初始化变量是一个很好的做法。 如果您不进行初始化,然后在未设置初始值的情况下在代码中使用它们,则变量将以可能会“破坏”代码的随机值开头。 该值将是加载程序时内存中的值。
有关Ints的更多信息 ( More about Ints )
What is the biggest number an int can store?. Well, it depends on the type of CPU but it is generally accepted as 32 bits. Because it can hold almost as many negative values as positive, the range of values is +/- 2-32 to 232 or -2,147,483,648 to +2,147,483,647.
一个int可以存储的最大数量是多少? 。 好吧,这取决于CPU的类型,但通常被接受为32位。 因为它可以容纳几乎与正数一样多的负值,所以值的范围为+/- 2 -32至2 32或-2,147,483,648至+2,147,483,647。
This is for a signed int, but there is also an unsigned int that holds zero or positive. It has a range of 0 to 4,294,967,295. Just remember – unsigned ints don’t need a sign (like + or -1) in front of them because they are always positive or 0.
这是针对有符号的int,但也有一个无符号的 int,它保持零或正数。 它的范围是0到4,294,967,295。 请记住 -无符号整数不需要在它们前面加一个符号(例如+或-1),因为它们始终为正或0。
短整数 ( Short Ints )
There is a shorter int type, coincidentally called short int which uses 16 bits (2 bytes). This holds numbers in the range -32768 to +32767. If you use a large umber of ints, you can possibly save memory by using short ints. It will not be any quicker, despite being half the size. 32 Bit CPUs fetch values from memory in blocks of 4 bytes at a time. I.e. 32 bits (Hence the name- 32 Bit CPU!). So fetching 16 bits still requires a 32 bit fetch.
有一个较短的int类型,巧合地称为short int,它使用16位(2个字节)。 该数字范围为-32768至+32767。 如果您使用大量的整数,则可以使用简短的整数来节省内存。 尽管尺寸只有一半,但速度不会更快。 32位CPU一次以4个字节的块的形式从内存中获取值。 即32位(因此命名为32位CPU!)。 因此,获取16位仍需要32位获取。
There is a longer 64 bit called long long in C. Some C++ compilers while not supporting that type directly use an alternate name- e.g. both Borland and Microsoft use _int64. This has a range of -9223372036854775807 to 9223372036854775807 (signed) and 0 to 18446744073709551615 (unsigned).
在C语言中,有一个较长的64位称为long long 。某些不支持该类型的C ++编译器直接使用替代名称-例如Borland和Microsoft都使用_int64 。 其范围是-9223372036854775807至9223372036854775807(带符号)和0至18446744073709551615(无符号)。
As with ints there is an unsigned short int type that has a range of 0..65535.
与int一样,存在无符号short int类型,其范围为0..65535。
Note: Some computer languages refer to 16 bits as a Word.
注意 :某些计算机语言将16位称为Word。
精密算术 ( Precision Arithmetic )
双重麻烦 ( Double Trouble )
There’s no long float, but there is a double type that is twice as big as float.
没有长浮点数,但是有一个双精度类型,它是浮点数的两倍。
Float: Occupies 4 bytes. Range 17×10-38 to 1.7×1038
浮点数 :占用4个字节。 范围17×10 -38至1.7×10 38
Double: Occupies 8 bytes. Range 3.4×10-308 to 3.4308
双精度:占用8个字节。 范围3.4×10 -308到3.4 308
Unless you’re doing scientific programming with very large or small numbers, you’ll only use doubles for greater precision. Floats are good for 6 digits of accuracy but doubles offer 15.
除非您使用非常大或很小的数字进行科学编程,否则只会使用双精度来提高精度。 浮点数可提供6位数的精度,但双精度浮点数提供15。
精确 ( Precision )
Consider the number 567.8976523. It is a valid float value. But if we print it out with this code below you can see lack of precision appearing. The number has 10 digits but is being stored in a float variable with only six digits of precision.
考虑数字567.8976523。 这是有效的浮点值。 但是,如果我们在下面的代码中将其打印出来,您会发现缺乏精度。 该数字有10位数字,但存储在float变量中,精度只有6位数字。
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
float value = 567.8976523;
cout.precision(8) ;
cout << value << endl;
return 0;
}
See About Input and Output for details on how cout works, and how to use precision. This example sets the output precision to 8 digits. Unfortunately floats can only hold 6 and some compilers will issue a warning about converting a double to a float. When run, this prints out 567.89764
有关cout的工作方式以及使用精度的详细信息,请参见关于输入和输出 。 本示例将输出精度设置为8位数字。 不幸的是,浮点数最多只能容纳6个,并且某些编译器会发出有关将double转换为float的警告。 运行时,将打印出567.89764
If you change the precision to 15, it prints as 567.897644042969. Quite a difference! Now move the decimal point two to the left so the value is 5.678976523 and rerun the program. This time it outputs 5.67897653579712. This is more accurate but still different.
如果将精度更改为15,则打印为567.897644042969。 完全不同! 现在,将小数点后两位向左移动,以便该值为5.678976523,然后重新运行该程序。 这次输出5.67897653579712。 这更准确,但仍然不同。
If you change the type of value to double and the precision to 10 it will print the value exactly as defined. As a general rule, floats are handy for small, non integer numbers but with more than 6 digits, you have to use doubles.
如果将值的类型更改为double并将精度更改为10,则将完全按照定义打印该值。 通常,浮点数适用于较小的非整数,但位数超过6位,则必须使用双精度。
了解算术运算 ( Learn about Arithmetic Operations )
Writing computer software wouldn’t be much use if you couldn’t do addition, subtraction etc. Here’s example 2.
如果您不能进行加法,减法等操作,那么编写计算机软件的用处就不会太大。这是示例2。
// ex2numbers.cpp
//
#include <iostream>
using namespace std;
int main()
{
int a=9;
int b= 12;
int total=a+b;
cout << "The total is " << total << endl;
return 0;
}
示例2的说明 ( Explanation of Example 2 )
Three int variables are declared. A and B are assigned values, then total is assigned the sum of A and B.
声明了三个int 变量 。 为A和B分配值,然后为total分配A和B的总和。
在运行此示例之前 ( Before running this example )
Here’s a little tip to save time when running Command Line applications.
这是在运行命令行应用程序时节省时间的一些技巧。
When you run this program from the Command Line, it should output “The number is 22”.
当您从命令行运行该程序时,它应输出“数字为22” 。
其他算术运算 ( Other Arithmetic Operations )
As well as addition, you can do subtraction, multiplication and division. Just use + for addition, – for subtraction, * for multiplication and / for division.
除加法外,您还可以进行减法,乘法和除法。 只需将+用于加法,将-用于减法,将*用于乘法和/除法。
Try changing the above program- use subtraction or multiplication. You can also change ints to floats or doubles.
尝试更改上述程序-使用减法或乘法。 您还可以将int更改为float或double 。
With floats, you have no control over how many decimal points are displayed unless you set the precision as shown earlier.
使用浮点数时,除非您如前所述设置精度,否则您无法控制显示的小数点数。
使用cout指定输出格式 ( Specifying Output Formats with cout )
When you’re outputting numbers, you need to think about these attributes of the numbers.
在输出数字时,需要考虑数字的这些属性。
- Width- How much space is needed for the entire number
宽度-整数需要多少空间
- Alignment – left or right- numbers tend to be right aligned
对齐-左或右数字趋于右对齐
- Number of decimal places
小数位数
- Sign or brackets for negative numbers.
负号的符号或方括号。
- Thousands Separators. Big numbers look ugly without these.
千位分隔符。 没有这些,大数字看起来很难看。
Now width, alignment, number of decimal places and signs can be set by the cout object and iomanip include file functions.
现在,宽度,对齐方式,小数位数和符号可以由cout对象和iomanip包含文件函数设置。
Thousands separators are a little more complicated. They are set from the locale of a PC. A locale contains information relevant to your country- such as currency symbols and decimal point and thousands separators. In the UK and USA, the number 100.98 uses a decimal point . as the decimal point whereas in some European countries it is a comma so €5,70 means a price of 5 Euros and 70 cents.
千位分隔符要复杂一些。 它们是从PC的语言环境设置的。 语言环境包含与您的国家/地区有关的信息,例如货币符号和小数点以及千位分隔符。 在英国和美国,数字100.98使用小数点。 作为小数点,而在某些欧洲国家中,这是逗号,因此€5,70表示价格为5欧元和70美分。
int main()
{
double a=925678.8750;
cout.setf(ios_base::showpoint|ios_base::right) ;
cout.fill('=') ;
cout.width(20) ;
locale loc("") ;
cout.imbue( loc ) ;
cout.precision(12) ;
cout << "The value is " << a << endl;
//cout.unsetf(ios_base::showpoint) ;
cout << left << "The value is " << a << endl;
for (int i=5;i< 12;i++) {
cout.precision(i) ;
cout << setprecision(i)<< "A= " << a << endl;
}
const moneypunct <char, true> &mpunct = use_facet <moneypunct <char, true > >(loc) ;
cout << loc.name( )<< mpunct.thousands_sep( ) << endl;
return 0;
}
The output from this is
输出是
=======The value is 925,678.875000
The value is 925,678.875000
A= 9.2568e+005
A= 925,679.
A= 925,678.9
A= 925,678.88
A= 925,678.875
A= 925,678.8750
A= 925,678.87500
English_United Kingdom.1252,
关于语言环境和Moneypunct ( About Locale and Moneypunct )
The example used a locale object from the PC in the line
该示例在该行中使用了来自PC的语言环境对象
locale loc("") ;
The line
线
const moneypunct <char, true> &mpunct = use_facet <moneypunct <char, true > >(loc) ;
creates an object mpunct which is a reference to a moneypunct template class. This has information about the specified locale – in our case, the thousands_sep() method returns the character used for thousands separator.
创建一个对象mpunct ,该对象是对moneypunct模板类的引用。 它具有有关指定语言环境的信息-在我们的例子中, 数千个(sep)方法返回用于千位分隔符的字符。
Without the line
没有线
cout.imbue( loc ) ;
There would be no thousand’s separators. Try commenting it out and rerunning the program.
不会有千位分隔符。 尝试将其注释掉并重新运行该程序。
Note There seem to be discrepancies between different compilers as to how cout.imbue behaves. Under Visual C++ 2005 Express Edition, this included separators. But the same code with Microsoft Visual C++ 6.0 did not!
注意不同的编译器之间似乎对cout.imbue的行为存在差异。 在Visual C ++ 2005 Express Edition下,这包括分隔符。 但是与Microsoft Visual C ++ 6.0相同的代码却没有!
小数点 ( Decimal Points )
The example on the previous page used showpoint to show trailing zeros after the decimal points. It output numbers in what is called standard mode. Other modes include
前一页的示例使用showpoint在小数点后显示尾随零。 它以所谓的标准模式输出数字。 其他模式包括
- Fixed Mode – Show numbers like 567.8
固定模式-显示数字如567.8
- Scientific Mode – Show numbers like 1.23450e+009
科学模式-显示数字,例如1.23450e + 009
If you use either of these two formatting modes through the cout.setf then precision() sets the number of decimal places after the decimal point (not the overall number of digits) but you lose the thousands formatting. Also trailing zeroes (as were enabled by ios_base::showpoint ) become automatically enabled without needing showpoint.
如果通过cout.setf使用这两种格式化方式中的任何一种,那么precision()会设置小数点后的小数位数(而不是位数的总数),但是会丢失成千上万种格式。 尾随零(由ios_base :: showpoint启用)也自动启用,而无需showpoint 。
需要注意的事情:整数,浮点数和布尔值 ( Things to Watch out for with ints, floats and bools )
Take a look at this statement.
看一下这句话。
float f = 122/11;
You’d expect something like a value of 11.0909090909. In fact, the value is 11. Why is this? because the expression on the right-hand side (known as an rvalue) is integer/integer. So it uses integer arithmetic which throws away the fractional part and assigns 11 to f. Changing it to
您可能希望得到的值是11.0909090909。 实际上,值是11。这是为什么? 因为右侧的表达式 (称为rvalue )是整数/整数。 因此,它使用整数算法,该算法舍弃了小数部分,并为f分配了11。 更改为
float f = 122.0/11
will correct it. It’s a very easy gotcha.
将纠正它。 这是一个非常简单的陷阱。
类型Bool和Int ( Types Bool and Int )
In C, there is no such type as a bool. Expressions in C were based on a zero being false or a non-zero being true. In C++ the type bool can take the values true or false. These values are still equivalent to 0 and 1. Somewhere in the compiler it will have a
在C语言中,没有布尔类型。 C语言中的表达式基于零为假或非零为真。 在C ++中, 布尔类型可以采用true或false值。 这些值仍然等于0和1。在编译器中的某个位置将有一个
const int false=0;
const int true= 1;
Or at least it acts that way! The two lines below are valid without casting so behind the scenes, bools are implicitly converted to ints and can even be incremented or decremented though this is very bad practice.
或者至少它是那样的! 下面的两行是有效的,无需强制转换,因此在后台将布尔值隐式转换为int,甚至可以递增或递减,尽管这是非常不好的做法。
bool fred=0;
int v = true;
Look at this code
看这段代码
bool bad = true;
bad++
if (bad) ...
The if will still do the if as the bad variable is non-zero but it is bad code and should be avoided. Good practice is to use them as they are intended. if (!v) is valid C++ but I prefer the more explicit if (v != 0). That, however, is a matter of taste, not a must-do directive.
if仍将执行if as坏变量,该变量为非零值,但这是坏代码,应避免使用。 优良作法是按预期使用它们。 if(!v)是有效的C ++,但我更倾向于if(v!= 0) 。 但是,这只是一个问题,而不是必须执行的指令。
使用枚举以获得更好的代码 ( Use Enums for Better Code )
For a more in depth look at enums, read this article first.
要更深入地了解枚举,请首先阅读本文。
What is an Enum?
什么是枚举?
An enum type provides a way to restrict a variable to one of a fixed set of values.
枚举类型提供了一种将变量限制为一组固定值之一的方法。
enum rainbowcolor {red,orange,green, yellow, blue,indigo,violet};
enum rainbowcolor {red=1000,orange=1005,green=1009, yellow=1010, blue,indigo,violet};
yellow=1010
黄色= 1010
You can assign an enum value to an int as in
您可以像下面这样将枚举值分配给int
int p=red;
rainbowcolor g=1000; // Error!
rainbowcolor g=red;
type safety
类型安全性
it is better for the compiler to catch errors at compile time than the user at runtime
,对于编译器而言,比在运行时用户捕获错误要好于编译时
Even though the two statements are conceptually the same. In fact you’ll usually find that these two seemingly identical lines
即使两个语句在概念上是相同的。 实际上,您通常会发现这两行看似相同
int p =1000;
rainbowcolor r = red;
That completes this tutorial. The next tutorial is about expressions and statements.
到此完成了本教程。 下一个教程是关于表达式和语句的。
翻译自: https://www.thoughtco.com/candand-handling-ints-and-floats-958408
c语言 整数和浮点数
原文地址: https://blog.csdn.net/cumao2792/article/details/108604352
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
相关文章