gpt4 book ai didi

c++ - for循环不执行

转载 作者:行者123 更新时间:2023-11-30 05:44:35 29 4
gpt4 key购买 nike

我使用简单的 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com