我编写了一个程序,用于以数组形式存储数字(由程序员预定义)。
例如,如果我要将数字1234存储在数组arrx [4]中,则其元素为:
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
Run Code Online (Sandbox Code Playgroud)
我尝试使用下面的代码来实现这一点:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int arrx[4]; // Stores the individual digits of number as array
int digx = 4; // Total number of digits in number
int i;
long int dupx = 1234; // Number which has to be stored in array
for(i = digx-1; i >= 0 ; i--)
{
arrx[digx-i-1] = int(dupx/pow(10,i));
dupx = dupx%(pow(10, i));
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试编译以上代码时,收到以下错误消息:
错误:类型为“ long int”和“ double”的无效操作数为二进制“ operator%”
我从上述误差中得出的唯一结论是问题出在模数运算符上。
因此,我心中有以下疑问
包含模运算符的代码到底有什么问题?
我怎样才能解决这个问题?
我正在将Code :: Blocks版本17.12与GNU GCC用作我的编译器。
mol*_*ilo 15
您只能%与整数一起使用,并pow产生浮点数。
您可以编写整数幂函数,也可以使用预定义的表,但是颠倒构造顺序并从最右边的数字开始比较简单:
int main()
{
int arrx[4]; //stores the individual digits of number as array
int digx = 4; //total number of digits in number
long int dupx = 1234; //number which has to be stored in array
for(int i = 0; i < digx; i++)
{
arrx[digx-i-1] = dupx%10;
dupx = dupx/10;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Bat*_*eba 13
std::pow 即使参数是整数类型,它也以各种形式返回浮点类型。
由于%需要整数参数,因此编译将失败。
使用(long)(pow(10,i))是一种解决方法,当然要检查(long)足够长的时间。请注意,即使在IEEE754 pow下也不需要返回可能的最佳浮点值,因此,截断to long有时可能是有害的。也许std::round紧随其后的是演员long。尽管当前的方式是考虑pow对整数参数的任何破坏都是有缺陷的。
在您的情况下,尽管我很想定义
constexpr/*use const on earlier standards*/ int powers[] = {1, 10, 100, 1000};
Run Code Online (Sandbox Code Playgroud)
并适当地编制索引。
| 归档时间: |
|
| 查看次数: |
863 次 |
| 最近记录: |