c++ - 在 C++ 的 while 循环中使用 pow() 函数

标签 c++ while-loop syntax-error pow

<分区>

注意:该程序与数学中的群论相关,但我需要的是该程序的帮助。如果是题外话,我很抱歉。

因此,任务是编写一个程序,找出用户输入 n 的 U(n) 元素的顺序。

元素 aU(n)={0<a<n: gcd(n,a)=1}

元素的顺序a U(n) 的最小正整数 z这样 (a^z)mod n=1

所以这就是 pow() 的位置while 中的函数循环进来。

我的代码如下:

#include<iostream>
#include<cmath>
using namespace std;

int gcd(int a, int b) //For finding the gcd to display the elements of U(n)
{
    int rem=1,c;
    while(rem!=0)
    {
        rem=a%b;
        a=b;
        b=rem;
    }
    return a;
}

int U(int c)    
{
    int el;
    cout<<"U("<<c<<") = {1";
    for(int i=2;i<=c;i++)    //This is for listing the elements of U(n)
    {
        if(gcd(c,i)==1)
        {
            cout<<","<<i;
        }
    }
    cout<<"}"<<endl;
    cout<<"Enter the element to check order: "<<endl; //The code for the order of element starts here
    cin>>el;
    int i=1;
    while(pow(el,i)%c!=1)   //This is the only part that is showing some error. I want to terminate the program as soon as it encounters the specific i such that (el^i)%c=1
    {
        i++;
    }
    cout<<"|"<<el<<"| = "<<i<<endl;
    return 0;
}

int main()
{
    int num,el;
    cout<<"Enter a integer: "<<endl;
    cin>>num;
    num=abs(num);
    U(num);
    return 0;
}

这就是全部代码。

我得到的错误是:

||In function 'int U(int)':|
|32|error: invalid operands of types '__gnu_cxx::__promote_2<int, int, double, double>::__type {aka double}' and 'int' to binary 'operator%'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 4 second(s)) ===|

我不是要此代码的替代或更简单版本,而是要解释为什么 pow() while 中的函数循环不工作以及如何使其正确

非常感谢。

最佳答案

因为您不能对 double 类型的值使用 % 运算符,这是 pow() 返回的值。

关于c++ - 在 C++ 的 while 循环中使用 pow() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52782138/

相关文章:

c++ - Win32 菜单项对齐

c - 不同 gcc 版本的语法错误?

lisp - 在结构的构造函数中指定多个选项?

c - 我用 c 语言做了一个计算器,当我尝试运行它时会弹出错误

c++ - 为什么不总是使用 fpic(位置无关代码)?

c++ - 替换 C++ 基类方法?

java - 需要在 while 循环内更新变量

java - 无法成功重新循环 while 循环

c++ - 异步使用 ReadDirectoryChangesW 时的线程死锁

java - 无限for循环