c - 为什么 pow() 从我的结果中减去 1?

标签 c math codeblocks

<分区>

我是 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);

如果运行此代码,您会发现 exponent_result 的输出是使用 pow() function 计算的, 总是从中减去 1。例如,如果 exponent_result 应该是 5^3 的结果, 结果将是 124而不是 125 .

我做错了什么?

仅供引用,我在文件的开头有这个。

#include <stdio.h>
#include <math.h>

最佳答案

pow浮点运算 中计算,可能实现为 pow(x, y) = exp(y * log(x)).

这可能导致结果“消失”:您可能得到一个略低于 125 的值,当 powdouble 返回类型时,该值被截断为 124被转换回 int

最简单的补救措施是为整型参数构建您自己的pow 函数。参见 The most efficient way to implement an integer based power function pow(int, int)

关于c - 为什么 pow() 从我的结果中减去 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45978528/

相关文章:

ruby - 如何在 Ruby 中将数字数组转换为矩阵

javascript - Jquery 计数

cocos2d-x - 在代码块中找不到 fontconfig/fontconfig.h

c - devc++程序执行失败

c - 带缓存的递归斐波那契计算 - 找不到错误

c - 在字符串中遇到空格后程序未写入文件

php - 网页不打印winsock信息

c - libexpect 程序在 CentOS7 上使用 SEGV 立即崩溃,在 CentOS6 上没有发生

java - 否定复杂的正则表达式

c - 有没有办法获取cmd提示符的文本文件?也就是说,printf 在代码块 c 中显示的所有数据?