我正在制作一个简单的程序,它抽象出复数和复数运算。我开始使用整数数据类型来解释我复杂数字的想象和真实方面,因为我在编码加法,减法和乘法成功之后我非常无知,我意识到对于除法我需要使用双精度。当我切换到双打时,我的前三次计算结果很差,当值存储为整数时,这些计算非常有用。有人可以向我解释一下c ++中的int和double有什么根本不同的东西让我的代码在int中工作正常但在我尝试使用双精度时会死掉吗?
我已粘贴我的代码供参考。
#include "Complex.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
Complex::Complex(){
real = 0;
imaginary = 0;
}
Complex::Complex(double givenReal, double givenImaginary)
{
real = givenReal;
imaginary = givenImaginary;
}
double Complex::getImaginary(){
return imaginary;
}
double Complex::getReal(){
return real;
}
double Complex::getMagnitude(){
//magnitude = sqrt(pow(real,2)+pow(magnitude,2));
return magnitude;
}
Complex Complex::operator+(Complex n){
Complex j = Complex();
j.real = real + n.real;
j.imaginary = imaginary + n.imaginary;
return j;
}
Complex Complex::operator-(Complex n){
Complex j = Complex();
j.real = real - n.real;
j.imaginary = imaginary - n.imaginary;
return j;
}
Complex Complex::operator*(Complex n){
Complex j = Complex();
j.real = (real * n.real)-(imaginary * n.imaginary);
j.imaginary = (real * n.imaginary) + (imaginary * n.real);
return j;
}
Complex Complex::operator/(Complex n){
Complex j = Complex();
j.real = ((real * n.real) + (imaginary * n.imaginary))/(n.real*n.real + n.imaginary*n.imaginary);
j.imaginary = ((imaginary*n.real)-(real * n.imaginary))/(n.real*n.real + n.imaginary*n.imaginary);
return j;
}
int main(){
Complex a = Complex(1, 3);
Complex b = Complex(4, 8);
Complex c = a+b;
printf("Adding a and b\nExpected: (5,11)\nActual: (%d,%d)\n",c.getReal(), c.getImaginary());
c = a-b;
printf("Subtracting b from a\nExpected: (-3,-5)\nActual: (%d,%d)\n",c.getReal(), c.getImaginary());
c = a*b;
printf("Multiplying a and b\nExpected: (-20,20)\nActual: (%d,%d)\n",c.getReal(), c.getImaginary());
c = a/b;
printf("Dividing a by b\nExpected: (.35,.05)\nActual: (%d,%d)\n",c.getReal(), c.getImaginary());
system ("pause");
}
输出:
添加a和b
预期:(5,11)
实际:(0,1075052544)
从中减去b
预期:( - 3,-5)
实际:(0,-1073217536)
乘以a和b
预期:( - 20,20)
实际:(0,-1070333952)
除以b b
预期:(。35,。05)
实际:(1610612736,1071015526)
答案 0 :(得分:3)
每个C / C ++程序员应该了解的printf
格式说明符是:%d
适用于int
,%f
适用于double
。