我是C编程的新手,我已经编写了这段代码,因为我已经被要求主要使用printf()和scanf()来做一些事情。我知道可以有更好的方法来解决这个问题,我很快就需要学习,但无论如何,现在这就是我所拥有的:
int add1, add2, exponent, exponent_result, multiplier, parenthese, product, sub, total;
printf("Let's try a slightly more complex calculation, in which we'll use an exponent.\n\n");
printf("Type 5 whole numbers or integers.\n\n");
scanf("%i %i %i %i %i", &add1, &add2, &exponent, &multiplier, &sub);
printf("Out of the numbers you typed, we're going to make this operation: (%i + %i^%i) * %i - %i\n\n", add1, add2, exponent, multiplier, sub);
exponent_result = pow(add2, exponent);
parenthese = add1 + exponent_result;
product = parenthese * multiplier;
total = (add1 + exponent_result) * multiplier - sub;
printf("Per PEMDAS, the correct order of operation is Parentheses, then Exponents, then Multiplications and Divisions, and finally Additions and Subtractions.\n\n");
printf("Therefore: (%i + %i^%i) * %i - %i\n\n", add1, add2, exponent, multiplier, sub);
printf("...is equal to: (%i + %i) * %i - %i\n\n", add1, exponent_result, multiplier, sub);
printf("...is equal to: %i * %i - %i\n\n", parenthese, multiplier, sub);
printf("...is equal to: %i - %i\n\n", product, sub);
printf("...is equal to: %i", total);
如果您运行此代码,您将意识到使用pow() function
计算的exponent_result的输出总是从中减去1。例如,如果exponent_result应该是5^3
的结果,那么结果将是124
而不是125
。
我做错了什么?
Fyi,我的文件开头有这个。
#include <stdio.h>
#include <math.h>
答案 0 :(得分:7)
pow
在浮点算术中进行评估,可能实现为pow(x, y) = exp(y * log(x))
。
这可能导致结果“熄灭”:您可能得到的值只有125,当double
的{{1}}返回类型转换回{pow
时,它会被截断为124 {1}}。
最简单的补救措施是为积分参数构建自己的int
函数。见The most efficient way to implement an integer based power function pow(int, int)