【C++】20. const char *str[]、指针的字节长度等 分析

在64位操作系统中,所有类型的指针都是8字节。

在32位操作系统中,所有类型的指针都是4字节。

对于const char *str[]={"aa","bbb" ,"1234567890"};,它的每个元素都是一个char*指针,所以它的每个元素占8字节。即:

sizeof(str[0])==8;
sizeof(str)/sizeof(str[0])==3;

字符型char占1个字节

整型int占4个字节

长整型long int占8个字节

sizeof(char)==1
sizeof(int)==4
sizeof(long int)==8

但是,所有指针类型都是8字节:

sizeof(char*)==8
sizeof(int*)==8
sizeof(long int*)==8

以下是例子:

#include 
// g++ -std=c++11 -pthread test.cpp -o test
int main() {
  const char *str[] = {"BLACK", "RED",     "YELLOW",
                       "GREEN", "UNKNOWN", "123456789"};
  unsigned int str_num = sizeof(str) / sizeof(str[0]);
  std::cout << "sizeof(str[0]= " << sizeof(str[0]) << std::endl;  //结果是 8
  std::cout << "sizeof(str[5]= " << sizeof(str[5]) << std::endl;  //结果是 8
  std::cout << "sizeof(str)= " << sizeof(str) << std::endl;  //结果是 6*8=48
  std::cout << "sizeof(str)/sizeof(str[0])= " << str_num
            << std::endl;  //结果是 48/8=6
  char *p1 = nullptr;
  int *p2 = nullptr;
  long int *p3 = nullptr;
  std::cout << "sizeof(p1)= " << sizeof(p1) << std::endl;  //结果是 8
  std::cout << "sizeof(char*)= " << sizeof(char *) << std::endl;
  std::cout << "sizeof(int*)= " << sizeof(int *) << std::endl;
  std::cout << "sizeof(p2)= " << sizeof(p2) << std::endl;  //结果是 8
  std::cout << "sizeof(p3)= " << sizeof(p3) << std::endl;  //结果是 8
  std::cout << "sizeof(char)= " << sizeof(char) << std::endl;  //结果是 1
  std::cout << "sizeof(int)= " << sizeof(int) << std::endl;    //结果是 4
  std::cout << "sizeof(long int)= " << sizeof(long int)
            << std::endl;  //结果是 8
  return 0;
}

C++ float转换int,四舍五入

正常的float 转换为 int 的情况是采用去尾巴的方式,也就是说去掉小数点后面的数值。

1. 常规的float 转换为 int :

例如: 9.34 = (int) 9 ; 9.99 = (int) 9 。

#include
int main()
{
 float i = 9.34;
 float j =  9.99;
 int a, b;
 a = (int) i;
 b = (int) j;
 printf("a = %d\n",a);
 printf("b = %d\n",b);
}

上面的输出结果为:

a = 9

b = 9

2. float 转换为 int 需要四舍五入提高精度,则基本算法如下:

在计算是特别要注意正负数的问题,另外要注意round()函数转换后虽然数值小数点后都变为了零,但此时还是float,还需要转换为 int。

#include
int main()
{
 float zer =  0;
 float i = 9.34;
 float j =  9.99;
 float k = -9.34;
 float m = -9.99;
 int a, b, c, d, e;
 int a1, b1, c1, d1, e1;
a = (int) (i * 10 + 5) / 10; 
b = (int) (j * 10 + 5) / 10; 
c = (int) (k * 10 - 5) / 10; 
d = (int) (m * 10 - 5) / 10; 
e = zer;
 a1 = (int)  round(i)
 b1 = (int)  round(j);
 c1 = (int)  round(k);
 d1 = (int)  round(m);
 e1 = (int) round(zer);
printf("a = %d\n",a); 
printf("b = %d\n",b); 
printf("c = %d\n",c); 
printf("d = %d\n",d); 
printf("e = %d\n",e);
printf("round a1 is %f\n", a1);
printf("round b1 is %f\n", b1);
printf("round c1 is %f\n", c1);
printf("round d1 is %f\n", d1);
printf("round e1 is %f\n", e1);
}

上面的输出结果为:

a = 9

b = 10

c = -9

d = -10

e = 0

round a1 is 9

round b1 is 10

round c1 is -9

round d1 is -10

round e1 is 0

本站内容来自用户投稿,如果侵犯了您的权利,请与我们联系删除。联系邮箱:835971066@qq.com

本文链接:http://news.xiuzhanwang.com/post/1943.html

发表评论

评论列表

还没有评论,快来说点什么吧~

友情链接: