zoukankan      html  css  js  c++  java
  • 注意C++中的int与long long 的乘法

    C++中(int)(long long)特别容易被忽略的点,在做乘法的时候即使单个变量在(int)范围内,如果乘积超了(int),也需要将乘数定义为(long long) 否则会出错!

    #include <bits/stdc++.h>
    using namespace std;
    
    int main(){
    	int i = 100000000;
    	long long j = 100000000;
    	cout << i*i << " " << sizeof(i*i) << " " << (long long)i*i << " " << sizeof((long long)i*i) << " " << i << endl;
    	cout << j*j << " " << sizeof(j*j) << " " << int(j*j) << " " << sizeof(int(j*j)) << " " << j << endl;	
    	return 0;
    }
    

    豆爸踩过的坑:

    洛谷P2415

    #include<bits/stdc++.h>
    
    using namespace std;
    typedef long long LL;
    const int N = 110;
    LL a[N];
    int n;
    LL res;
    
    int main() {
        //录入进来,终止条件是CTRL+D,最起码在CLion里是这样的.DevC++里试试ctrl+z
        while (cin >> a[++n]);
        n--;
        //找规律
        /**
         2,3
         元素个数n=2
         [2][3]
         [2,3]
         2出现2次,3出现2次。就元素都出现2^1次。
    
         2,3,4
         元素个数n=3
         [2][3][4]
         [2,3][2,4][3,4]
         [2,3,4]
         2出现4次,3出现4次,4出现4次,就元素都出现2^2次。
    
         发现规律:
         任意元素出现2^(n-1)次!
         */
    
        //暴力版本
        //for (int i = 1; i <= n; i++)res += a[i] * pow(2, n - 1);
    
        //位运算优化版本
        //for (int i = 1; i <= n; i++)res += (LL)a[i] * (1 << n - 1);
        for (int i = 1; i <= n; i++)res += a[i] * (1 << n - 1);
        /**
         C++中int和long long特别容易被忽略的点,在做乘法的时候即使单个变量在int范围内,如果乘积超了int,
         也需要将乘数定义为longlong 否则会出错
         */
    
        cout << res << endl;
        return 0;
    }
    
  • 相关阅读:
    Spring Jdbc事例说明(三)
    Spring 在+publicId+和+systemId+之间需要有空格
    Spring 开发环境搭建(二)
    Spring 基础概念——DI、IOC(一)
    SHELL字符串使用总结
    POSTGRESQL 创建表结构、修改字段、导入导出数据库(支持CSV)
    Spring+mybatis+postgresql整合
    Mybatis 自动生成代码,数据库postgresql
    POSTGRESQL 自动登录
    POSTGRESQL表分区
  • 原文地址:https://www.cnblogs.com/littlehb/p/14977432.html
Copyright © 2011-2022 走看看