在C++中使用 pow() 时出错
Error while using pow() in C++
我试图解决一个函数问题,在这个问题中,我必须计算数字 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);
相关文章:
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 在C++中如何在没有pow的情况下进行基础计算
- 为x86而非x64编译时出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 理解GCC中的std::pow实现
- 在C++中使用 pow() 时出错