c++ - for循环不执行

标签 c++ for-loop

我使用简单的 for 循环为复数(自制类)编写了一个朴素的(只接受整数指数)幂函数,该循环将原始数字的结果乘以 n 次:

C pow(C c, int e) {
    C res = 1;
    for (int i = 0; i==abs(e); ++i) res=res*c;
    return e > 0 ? res : static_cast<C>(1/res);
}

当我尝试执行此操作时,例如

C c(1,2);
cout << pow(c,3) << endl;

我总是得到 1,因为 for 循环没有执行(我检查过)。 这是完整的代码:

#include <cmath>
#include <stdexcept>
#include <iostream>
using namespace std;
struct C {
    // a + bi in C forall a, b in R
    double a;
    double b;
    C() = default;
    C(double f, double i=0): a(f), b(i) {}
    C operator+(C c) {return C(a+c.a,b+c.b);}
    C operator-(C c) {return C(a-c.a,b-c.b);}
    C operator*(C c) {return C(a*c.a-b*c.b,a*c.b+c.a*b);}
    C operator/(C c) {return C((a*c.a+b*c.b)/(pow(c.a,2)+pow(c.b,2)),(b*c.a - a*c.b)/(pow(c.a,2)+pow(c.b,2)));}
    operator double(){ if(b == 0) 
                        return double(a);
                       else 
                        throw invalid_argument(
                        "can't convert a complex number with an imaginary part to a double");}
};
C pow(C c, int e) {
    C res = 1;
    for (int i = 0; i==abs(e); ++i) {
        res=res*c;
        // check wether the loop executes
        cout << res << endl;}
    return e > 0 ? res : static_cast<C>(1/res);
}

ostream &operator<<(ostream &o, C c) { return c.b ? cout << c.a << " + " << c.b << "i " : cout << c.a;}

int main() {
C c(1,2), d(-1,3), a;
        cout << c << "^3 = " << pow(c,3) << endl;}

最佳答案

您写的内容将如下所示:

for (int i = 0; i == abs(e); ++i) 

initialize i with 0 and while i is equal to the absolute value of e (i.e. 3 at the beginning of the function call), do something

应该是

for (int i = 0; i < abs(e); ++i) 

提示:由于双重转换运算符(由 a*c.b + c.a*b 引起),代码将在第一次迭代时抛出异常,但这是另一个问题:修复你的复合体(即具有虚部)打印功能或实现 pretty-print 方法等。

关于c++ - for循环不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29744998/

相关文章:

matlab - Mat循环的for循环矢量处理RGB图像中的像素

scala - 在循环中填充 map [Scala]

javascript - 在每轮 javascript for 循环中显示 html 结果

c++ - 当系统路径作为参数传递给函数时无法获取转义字符

c++ - “Partial application” 模板参数

c++ - c++17 的 std::ptr_fun 替换

java - 如何杀死活细胞并复活活细胞而不弄乱计数器?康威生命游戏中的逻辑错误

c++ - 来自多项式类型的数字类型

c++ - 这种情况是否需要删除或创建新变量?

python - 如何在具有多个数据帧的字典中添加变量?