Codeforces 268B -未知值作为这个小c++程序的输出
Codeforces 268B - Unknown value as output for this small C++ program
下面是我试图解决的Codeforces问题的c++代码:
#include <iostream>
using namespace std;
int main()
{
int n = -1;
unsigned long long possible_combinations = 0;
cin >> n;
possible_combinations = (((n - 1) * n * (n + 1)) / 6) + n;
cout << possible_combinations;
return 0;
}
其中1 <= n <= 2000
.
对于n的小值它计算正确的值,但是当我使用2000
时,它显示- 18446744073611230851
。我只尝试了几个测试用例。
我知道公式是正确的,程序应该输出1333335000
,但它没有。代码有什么问题?
当您执行算术运算时,如果结果变得太大,则不会提升为更宽的类型。
由于n
是int
, 1
和6
是int
,所以整个计算都是用int
完成的。
1999 * 2000 * 2001是如此之大—7,999,998,000—以至于int
溢出。
始终使用unsigned long long
试试这个:
possible_combinations = (((unsigned long long) (n - 1) * n * (n + 1)) / 6) + n;
问题的原因很简单:如果n==2000
, (n - 1) * n * (n + 1)
对于int
来说太大(但是您的n
是int
,因此此表达式返回int
)。因此,您可以要求编译器使用更大的类型(语言不能自动使类型更宽)或只是更改n
的类型(使用unsigned long longn = -1;
而不是int n = -1;
)。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 使用mongocxx驱动程序时包含头文件问题
- 如何在c++程序中找到函数的地址