标签:style blog http color os io ar 2014 art
1 /* 2 * Main.c 3 * F6-结构-06. 复数四则运算 4 * Created on: 2014年8月26日 5 * Author: Boomkeeper 6 ********部分通过*********** 7 */ 8 9 #include <stdio.h> 10 #include <math.h> 11 12 #define EPSINON 0.1 13 14 /* 15 * 复数结构体,c1、c2对应于题目中的c1、c2 16 */ 17 struct complexNumber { 18 float real; 19 float imaginary; 20 } c1, c2; 21 22 /* 23 * 按照“(a1+b1i) 运算符 (a2+b2i) = 结果”的格式顺序输出2个复数 24 * ch对应于"+" "-" "*" "/"4个运算符 25 */ 26 void printComplex(struct complexNumber c1, char ch, struct complexNumber c2) { 27 28 if (c1.imaginary < 0) { 29 if (c2.imaginary < 0) 30 printf("(%.1f%.1fi) %c (%.1f%.1fi) = ", c1.real, c1.imaginary, ch, 31 c2.real, c2.imaginary); 32 if (c2.imaginary > 0) 33 printf("(%.1f%.1fi) %c (%.1f+%.1fi) = ", c1.real, c1.imaginary, ch, 34 c2.real, c2.imaginary); 35 } else if (c1.imaginary > 0) { 36 if (c2.imaginary < 0) 37 printf("(%.1f+%.1fi) %c (%.1f%.1fi) = ", c1.real, c1.imaginary, ch, 38 c2.real, c2.imaginary); 39 if (c2.imaginary > 0) 40 printf("(%.1f+%.1fi) %c (%.1f+%.1fi) = ", c1.real, c1.imaginary, ch, 41 c2.real, c2.imaginary); 42 } 43 } 44 45 /* 46 * 输出2个复数的和、差、积、商 47 */ 48 void printResult(float re, float im) { 49 50 if (fabs(re) < EPSINON) 51 re = 0; 52 if (fabs(im) < EPSINON) 53 im = 0; 54 55 if (re == 0 && im == 0) 56 printf("0.0\n"); 57 else { 58 if (re != 0 && im > 0) 59 printf("%.1f+%.1fi\n", re, im); 60 if (re != 0 && im < 0) 61 printf("%.1f%.1fi\n", re, im); 62 if (re != 0 && im == 0) 63 printf("%.1f\n", re); 64 if (re == 0 && im != 0) 65 printf("%.1fi\n", im); 66 } 67 } 68 69 int main(void) { 70 71 float re = 0, im = 0; //临时变量,计算实部和虚部 72 73 scanf("%f %f %f %f", &c1.real, &c1.imaginary, &c2.real, &c2.imaginary); 74 75 //和 76 printComplex(c1, ‘+‘, c2); 77 re = c1.real + c2.real; 78 im = c1.imaginary + c2.imaginary; 79 printResult(re, im); 80 81 //差 82 printComplex(c1, ‘-‘, c2); 83 re = c1.real - c2.real; 84 im = c1.imaginary - c2.imaginary; 85 printResult(re, im); 86 87 //积 88 printComplex(c1, ‘*‘, c2); 89 re = c1.real * c2.real - c1.imaginary * c2.imaginary; 90 im = c1.real * c2.imaginary + c1.imaginary * c2.real; 91 printResult(re, im); 92 93 //商 94 printComplex(c1, ‘/‘, c2); 95 re = (c1.real * c2.real + c1.imaginary * c2.imaginary) 96 / (c2.real * c2.real + c2.imaginary * c2.imaginary); 97 im = (c1.imaginary * c2.real - c1.real * c2.imaginary) 98 / (c2.real * c2.real + c2.imaginary * c2.imaginary); 99 printResult(re, im); 100 101 return 0; 102 }
1.这个题目最让我抓心的是复数的虚部的符号的输出,复数四则运算还好计算,就是这个正负号,一不小心就乱了;
2.浮点数与0的比较,针对这道题目,因为输出结果只需要精确到0.1,所以<=0.1 && >=-0.1就判断为0。起初我参考了其他文章,按照0.00001来判断,输出结果总是不合题意。
题目链接:
http://pat.zju.edu.cn/contests/basic-programming/%E7%BB%93%E6%9E%84-06
参考:
http://blog.csdn.net/rabbit8848/article/details/30284651
http://blog.sina.com.cn/s/blog_64a475370101119h.html
标签:style blog http color os io ar 2014 art
原文地址:http://www.cnblogs.com/boomkeeper/p/F6.html