我是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);
Run Code Online (Sandbox Code Playgroud)
如果运行此代码,您将意识到exponent_result的输出(使用它计算)pow() function
总是从中减去1.例如,如果exponent_result应该是结果5^3
,那么结果将是124
而不是125
.
我究竟做错了什么?
Fyi,我在我的文件开头有这个.
#include <stdio.h>
#include <math.h>
Run Code Online (Sandbox Code Playgroud)
pow
在浮点运算中进行计算,可能实现为pow(x, y) = exp(y * log(x))
.
这可能导致结果"熄灭":您可能得到的值只有125,当double
返回类型pow
转换回时,它会被截断为124 int
.
最简单的补救措施是pow
为积分参数构建自己的函数.请参阅实现基于整数的幂函数pow(int,int)的最有效方法