【问题标题】:Why `pow(sum,1/2)` is not giving me the same result as `sqrt(sum))`?为什么 `pow(sum,1/2)` 没有给我与 `sqrt(sum))` 相同的结果?
【发布时间】:2020-08-10 11:24:39
【问题描述】:

在最后的代码中,底部有一个名为general_norm 的函数,它使用了以下print() 函数:

printf(" %f",sqrt(sum));
printf(" %f",pow(sum,1/2));

虽然sqrt(sum)) 给了我正确的结果,但我不明白为什么pow(sum,1/2) 不考虑√x = x½。

你能帮我弄清楚我错过了什么吗?谢谢! :-)

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


void print_vector(int N,float * V);
void save_vector(int N,float * V);
void absolute_values(int N,float * V, float * VABS);
void maximum_value(int N, float * VABS);
void general_norm(int N, float * VABS);


int main(void)
{

    const int n=4;
    int i;
    float v[n],vabs[n];

    puts("Enter the 5 components of the vector:");
    save_vector(n, v);

    puts("\nThe vector is:");
    print_vector(n, v);

    puts("\nThe absolute vector is:");
    absolute_values(n, v, vabs);

    puts("\nThe maximum value is:");
    maximum_value(n, vabs);

    puts("\nThe general norm is:");
    general_norm(n, vabs);

    return 0;
}

void save_vector(int N, float * V)
{
    int i;
    for(i=0;i<N;i++)
        scanf("%f",V+i);
}

void print_vector(int N, float * V)
{
    int i;
    for(i=0;i<N;i++)
        printf(" %.2f ",*(V+i));
}

void absolute_values(int N, float *V, float *VABS)
{
    int i;
    for(i=0;i<N;i++)
    {
        VABS[i]=((V[i]<0)?-V[i]:V[i]);
        printf(" %f", VABS[i]);
    }
}

void maximum_value(int N, float * VABS)
{
  int i;
  float maximum;
  maximum = VABS[0];

  for (i = 1; i < 4; i++)
  {
    if (VABS[i] > maximum)
    {
       maximum = VABS[i];
    }
  }
  printf(" %f", maximum);
}

void general_norm(int N, float * VABS)
{
  int i;
  float sum;

  for (i = 0; i < 4; i++)
    {
    sum=sum+pow(VABS[i],2);
    }
  printf(" %f",sqrt(sum));
  printf(" %f",pow(sum,1/2));
}

【问题讨论】:

  • 整数数学。 1/2 为 0。要么使用 0.5,要么强制类型为 1.0 / 2.0。
  • 非常感谢@1201ProgramAlarm。我刚刚将您的答案添加为下面的最后一个。再次感谢您的快速帮助!! :-)
  • 您也不应该期望sqrt(x) 完全等于pow(x, 0.5); pow 通常使用不同的算法,一般来说,这种算法不太准确。 (如果它在您的计算机上完全相等,这可能意味着 pow 实现注意到第二个参数 0.5 并调用 sqrt。)
  • 旁白:printf("Enter the %d components of the vector:\n", n); 比 puts("Enter the 5 components of the vector:"); 更有意义
  • 提示:为了更深入地了解sqrt(sum), pow(sum,0.5) 的潜在差异,请使用指数符号:printf(" %e",sqrt(sum) - pow(sum,0.5));

标签: c square-root


【解决方案1】:

把 1201ProgramAlarm 给我的答案留在这里:

整数数学。 1/2 是 0。要么使用0.5,要么强制输入1.0 / 2.0。

1.0 / 2 也可以。

【讨论】:

    猜你喜欢
    • 2015-08-24
    • 2014-09-21
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 2021-11-13
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多