C++代码输出负值
C++ code outputting negative values
我为一个谜题类型的网站写了一个解决方案。在具有最新g ++的XCode上,我的代码编译良好。在他们的网站(和代码板(上,我的输出是负数。有人可以帮助我理解为什么,因为我真的被难住了。
#include <iostream>
#include <cmath>
#include <vector>
#include <map>
using namespace std;
vector<int> getAllPrimes(vector<int> primesArray, int n)
{
vector<int> numArray (n+1, 1);
for (int i = 2; i <= n; i++)
{
if (numArray[i] == 1)
{
primesArray.push_back(i);
for (int k = i; k <= n; k+= i)
{
numArray[k] = 0;
}
}
}
return primesArray;
}
int main()
{
long n = 32327;
if (n == 1)
{
printf("%ldn", n);
return EXIT_SUCCESS;
}
map <int, int> primeMap;
map <int, int>::iterator itr;
vector<int> primesArray;
primesArray = getAllPrimes(primesArray, n);
while(!primesArray.empty())
{
long currPrime = primesArray.back(), curr = currPrime;
while (currPrime <= n)
{
primeMap[curr] += (int)floor(n/currPrime);
currPrime *= curr; //multiply currPrime to add another factor of curr.
}
primesArray.pop_back();
}
//get the number of divisors of n!
long numDivisors = 1;
for (itr=primeMap.begin(); itr != primeMap.end(); itr++)
{
numDivisors *= ((*itr).second*2)+1; //power of each prime + 1, * 2 because you need the number of divisors of the square of n!
numDivisors = numDivisors % 1000007;
}
printf("%ldn", numDivisors);
return 0;
}
通常"long n"应该从标准输入中读取 1 到 100 万之间的整数,但我只是分配了一个值来模拟它。
我在这里将代码放在代码板中:http://codepad.org/RpPFuLzX。如您所见,输出是 -596936
,而在我的机器上它是656502
(这是正确的输出(。到底是怎么回事?
很可能是 CodePad 和其他站点在 32 位系统上编译,其中long
长度为 4 字节 (http://codepad.org/W00vCFIN(。在OS X上,所有内容默认为64位,在这些系统(但不是Windows(上,long为8字节长。因此,您在某个时候溢出了计算。
如果依赖于特定的整数大小,请使用 stdint.h
这是一个改编版本,它符合您的预期输出,使用int64_t
: http://codepad.org/Owsl3ClR
您获得不同结果的原因是,像 long 这样的数据类型在 32 位和 64 位上的处理方式不同。Mac OS X 使用 LP64 数据模型,其中 long 在 64 位模式下为 64 位,在 32 位模式下为 32 位。如果分别为 32 位和 64 位构建程序,您将看到不同的结果。
一种流行的解决方案是使用指定位数的数据类型,例如uint64_t
用于大小为 64 位的无符号整数,而不是根据标准刚好等于或大于 int 的long
。
在线粘贴到科莫,我得到:
"ComeauTest.c", line 49: error: more than one instance of overloaded function
"floor" matches the argument list, the choices that match are:
function "floor(long double)"
function "floor(float)"
function "floor(double) C"
function "std::floor(long double)"
function "std::floor(float)"
The argument types that you used are: (long)
primeMap[curr] += (int)floor(n/currPrime);
相关文章:
- 为什么我的代码在输出中增加了93天
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 我无法获取以下代码的输出
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 编译并运行后,输出未出现在 Visual Studio 代码中
- VI工作室代码错误无法打开输出文件主.exe
- 代码编译没有任何输出,入门程序
- 与其他编译器相比,相同的代码在工作室Microsoft提供不同的输出
- 可能我知道为什么这段代码没有给出任何输出吗?
- 从排序数组中删除重复项,具有不同代码方式的相同解决方案具有不同的输出
- Clang 给了我符号更改的警告,但代码仍然产生正确的输出
- 为什么这两个版本的代码给出不同的输出
- 以下与指针相关的代码的输出是什么?
- C++和 Python 中的代码相同,但输出不同
- 为什么我的代码块上没有显示输出?
- C++ 高级代码未给出正确的输出
- (C++)分解这个简单的输入/输出代码:
- 错误的输出代码
- 奇怪的输出(代码块codebblocks -16.01mingw-setup.exe)