c-在VS代码终端给出错误的代码输出


#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct Node
{
int coef;
struct Node *ptr;
} node;
void createLinkList(node **head, int degree){
node *temp, *last, *tempHead;
tempHead = (node *)malloc(sizeof(node));
tempHead->ptr = NULL;
scanf("%d", &(tempHead->coef));
last = tempHead;
for (int i = 1; i < degree + 1; i++){
temp = (node *)malloc(sizeof(node));
scanf("%d", &(temp->coef));
temp->ptr = NULL;
last->ptr = temp;
last = temp;}
*head = tempHead;}
int findVal(node *head, int degree, int x){
int result = 0;
while (head != NULL){
result += (head->coef) * pow(x, degree);
head = head->ptr;
degree--;}
return result;}
int main()
{
node *head;
int power;
int x;
scanf("%d",&power);
createLinkList(&head,power);
scanf("%d",&x);
int k = findVal(head,power,x);
printf("k = %d",k);
// int n = 4*pow(5,2);
// printf("n = %d",n);
}

这里有一个简单的C语言代码。createLinkList()函数用于创建链表,findVal()用于评估多项式。

对于x的其他值,我的代码运行良好,但每当我取x=5时,代码就会给出错误的输出。

例如,如果我取:n=2,coeffe=4,0,5和x=5(相当于在一行中输入如下:2 4 0 5 5(,那么输出(k的值(显然应该是105(4*(x^2(+0*(x^1(+5(。

但在我的终端输出中显示104。您可以在IDE中检查此代码。据我所知,createLinkList((函数没有问题。

有人能告诉我为什么会发生这种事吗?

您正在将稍微偏离的结果截断为更不正确的结果。使用某种舍入而不是截断。


虽然我不能重现这个问题,但问题肯定是pow没有准确返回结果。

pow(x, y)不能简单地使用将x自身乘以y的循环,至少不总是这样。这有三个原因。

  • y不必是整数。考虑y2.4的情况。你会循环多少次?

  • 小数不能用浮点数准确表示是很常见的。例如,1/10、2/10、3/10、4/10、6/10、7/10、8/10和9/10都是二进制的周期数(就像1/3是十进制的(,所以它们不能用浮点数准确地表示。该循环中的每一次乘法都会加剧CCD_ 10表示中的任何不准确性。如果你对复利有任何了解,那么你就会知道复利可以很快放大小额。

  • 对于较大的CCD_ 11值,这将是非常低效的。

所以在内部,pow是通过其他方法计算结果的,而这种方法并不能产生正确的结果。它可能只减少了不到0.00000000000000001(真实的(。问题是,当您将这个数字转换为int时,您会截断它。实际上是4.99999999999999999的5突然变成了4(例如(,您的最终结果是1。

与其截断,不如使用某种舍入。

最新更新