在C++中使用 pow() 时出错

Error while using pow() in C++

本文关键字:出错 pow C++      更新时间:2023-10-16

我试图解决一个函数问题,在这个问题中,我必须计算数字 1 出现在所有小于 n(given( 的非负整数中的次数。

这是我的代码:

int ones(int n, int d)
{
int rounddown = n - n % pow(10, d+1);
int roundup = rounddown + pow(10, d+1);
int right = n % pow(10, d);
int dig = (n/pow(10, d)) % 10;
if(dig<1)
return rounddown/10;
else if(dig==1)
return rounddown/10 + right + 1;
else
return roundup/10;
}
int countDigitOne(int n) {
int count = 0;
string s = to_string(n);
for(int i=0;i<s.length();i++)
count+=ones(n, i);   
return count;        
}

但是出现了以下编译错误:

第 3 行:类型为 '__gnu_cxx::__promote_2::__type {aka double}' 和 'int' 到二进制 'operator%' 的无效操作数

主要问题是类型转换。pow的结果是double.取模运算符不适用于double。你需要采取fmod.

像这样修复你的第 3 行:

int rounddown = (int)(n - fmod(n, pow(10, d +1));

由于您的值都在integer域中,因此您还可以使用:

int rounddown = n - n % (int)(pow(10, d + 1));

正如其他人所建议的那样。


只是为了完整...如果您没有被迫使用算术方法,您可以char比较:

#include<iostream>
#include<string>
using namespace std;
int countOnesInNumber(string s)
{
int res = 0;
for(int i = 0; i < s.length(); i++)
{
if(s[i] == '1')
{
res++;
}
}
return res;
}
long countOnes(int upper)
{
long result = 0;
for(int i = 0; i < upper; i++)
{
result += countOnesInNumber(std::to_string(i));
}
return result;
}
int main()
{
string in;
cout << "Please enter a number:";
cin >> in;
cout << endl;
cout << "you choose:" << in << endl;
int n = stoi(in);
cout << "there are " << countOnes(n) << " ones under " << n << endl;
cin.ignore();
cin.get();
}

还有一种更复杂的方法。数字对每个量级重复。有 1 个 1 下 10,有 10 乘以 1 一个低于 100 加上另外 10 个数字 10...19。等等。你可以用以下方法计算给定量级下的一的数量:

int exp = (int)log10(n);
int ones = exp * (int)pow(10, exp - 1);

其中n必须是 10 的星等(例如 10、100、1000、10000 ...如果你擅长数学,你甚至可能会找到一个完整的封闭公式。

函数pow返回双精度值。取模操作在整数之间,因此错误 - 您正在尝试在 int 和双精度之间使用取模。解决它的一种方法是使用强制转换:

int rounddown = n - n % (int)pow(10, d + 1);

正如其他人所说,对整数使用pow函数以及从double转换为int效率低下,并可能导致错误。我建议(通过同意 Tyler V 的建议(你实现这个简单的递归整数 pow:

int ipow(int a, int b){
if (b == 0)
return 1;
return a * ipow(a,b - 1);
}

这仅适用于正整数a,b但我认为就您的目的而言就足够了。现在你可以写

int rounddown = n - n % ipow(10, d + 1);