欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

整数相乘容易出错实例 博客分类: c++  

程序员文章站 2024-03-19 10:16:46
...

 

///



/* 1、测试 两个 int32 整数相乘,结果放保存在uint64整数,测试输出结果是否正确
 * 2、
 * 3、
 *
 * date: 2018-05-25
 */

#include <iostream>
#include <fstream>
#include <vector>
#include <stdio.h>
#include<stdlib.h>
#include<string>

using uint32 = unsigned int;
using uint64 = unsigned long long int;
using uint8 = unsigned char;


const uint64 K_512 = 512 * 1024;
const uint64 K_1024 = 1024 * 1024;

uint64 MAX_MEM = 3 * 1024 * K_1024;

//uint64 MAX_MEM = 3;

/// first argv: original string
int main(int argc, char** argv)
{

    uint64 value_64 = 0;

    uint32 v1 = 1024 * 1024 * 1024;
    uint32 v2 = 5;
    value_64 = v1 * v2;

    std::cout << "32位整数 * 32位整数 :\n" ;
    std::cout << " v1 * v2 = " << v1 * v2 << std::endl;
    std::cout << "value_64 = " << value_64 << std::endl;
    std::cout << std::endl;

    uint32 v3 = 1024 * 1024 * 1024;
    uint64 v4 = 5;
    value_64 = v3 * v4;

    std::cout << "32位整数 * 64位整数 : \n" ;
    std::cout << " v3 * v4 = " << v3 * v4 << std::endl;
    std::cout << "value_64 = " << value_64 << std::endl;
    std::cout << std::endl;

    uint64 v5 = 1024 * 1024 * 1024;
    uint32 v6 = 5;
    value_64 = v5 * v6;

    std::cout << "64位整数 * 32位整数 : \n" ;
    std::cout << " v5 * v6 = " << v5 * v6 << std::endl;
    std::cout << "value_64 = " << value_64 << std::endl;


}

    结果:

      32位整数 * 32位整数 :
      v1 * v2 = 1073741824
      value_64 = 1073741824

      32位整数 * 64位整数 :
       v3 * v4 = 5368709120
      value_64 = 5368709120

      64位整数 * 32位整数 :
       v5 * v6 = 5368709120
      value_64 = 5368709120