设为首页 加入收藏

TOP

C++自学之路:3.1-简单变量(一)
2017-07-20 10:22:47 】 浏览:3294
Tags:自学 3.1- 简单 变量

C++自学之路:3.1-简单变量。

#include 
  
   
#include 
   
     int main(int argc, const char * argv[]) { using namespace std; int n_int = INT_MAX; short n_short = SHRT_MAX; long n_long = LONG_MAX; long long n_llong = LLONG_MAX; cout << "int is " << sizeof(n_int) << " bytes." << endl; cout << "short is " << sizeof(n_short) << " btyes." << endl; cout << "long is " << sizeof(n_long) << " bytes." << endl; cout << "long long " << sizeof(n_llong) << " bytes." << endl; cout << endl; cout << "Maxium values:" << endl; cout << "int:" << n_int << endl; cout << "short:" << n_short << endl; cout << "long:" << n_long << endl; cout << "long long:" << n_llong << endl; cout << "Minium int values:" << endl; cout << "Bits per byte = " << CHAR_BIT << endl; return 0; }
   
  
sizeof 指出,在使用8位字节的 系统中,int长度为4个字节,可以对类名或者变量名使用sizeof运算符,类名需要放在括号中,变量名括号可选。
cout << "short is " << sizeof(int) << " btyes." << endl;

cout << "short is " << sizeof n_short << " btyes." << endl;

 

#include 
  
   
#define ZERO 0;
#include 
   
     int main(int argc, const char * argv[]) { using namespace std; short sam = SHRT_MAX; unsigned short sue = sam; cout << "Sam has " << sam << " dollars and Sue has " << sue; cout << " dollars deposited." << endl << "Add $1 to each accout." << endl << "Now "; sam = sam + 1; sue = sue + 1; cout << "Sam has " << sam << " dollars and Sue has " << sue; cout << " dollars deposited.\nPoor Sam!" << endl; sam = ZERO; sue = ZERO; cout << "Sam has " << sam << " dollars and Sue has " << sue; cout << " dollars deposited." << endl; cout << "Take $1 from each accout." << endl << "Now "; sam = sam - 1; sue = sue - 1; cout << "Sam has " << sam << " dollars and Sue has " << sue; cout << " dollars deposited." << endl << "Lucky Sue!" << endl; return 0; } 
   
  
运行结果:
Sam has 32767 dollars and Sue has 32767 dollars deposited.
Add $1 to each accout.
Now Sam has -32768 dollars and Sue has 32768 dollars deposited.
Poor Sam!
Sam has 0 dollars and Sue has 0 dollars deposited.
Take $1 from each accout.
Now Sam has -1 dollars and Sue has 65535 dollars deposited.
Lucky Sue!

short 变量sam 和 unsigned short 变量 sue,分别设置最大值和最小值。short变量从最大值加1,取值从32768变成—32769。unsigned short变量从最大值加1并没有什么问题。short变量从最大值减1,没什么问题。unsigned short变量从最大值加1,从0变为65535。
如果超越了范围,其值将从范围另一端取值。

无符号类型:
unsigned short change;
unsigned int rovert;
unsigned quarterback;//unsigned 本身是 unsigned int 缩写。
unsigned long gone;
unsigned long long lang_lang;
//无符号类型的正值更大。

选择整型类型:
1.int 被设置为对目标计算机而言最为自然的长度。
2.如果变量表示的值不可能为负,如文档中的字数,则可以使用无符号类型,这样可以表示更大的值。

 

 

#include 
  
   

using namespace std;

int main(int argc, const char * arvg[]) {
    
    using namespace std;
    in
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++编程开发基础知识学习 下一篇C/C++_多和多线程_demo1

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目