【问题标题】:How to use sin, tan, cos, and sec in C program?C程序中如何使用sin、tan、cos、sec?
【发布时间】:2015-07-26 23:19:48
【问题描述】:

我正在使用此链接上的公式制作计算器: http://cereference.com/book/surveying-and-transportation-engineering/simple-curves-or-circular-curves#sthash.qrD1VOm6.08csgYq9.dpbs

https://www.easycalculation.com/engineering/civil/highways-horizontal-curve.php

已编辑问题!

所以我使用 math.h 库来使用 sin、tan、cos 和 sec 函数,但根据我的公式,答案不正确......所以要测试,假设我的角度为 36和 286 的半径......所以切线(切线)的答案必须是 92.927。我的下一个问题是如何使用 sec 函数?我评论它是因为它不会编译...还有 tan、sin 和 cos。

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


int main(){

double length, angle, radius, tangent, chord, midordinate, external, degree;
double pcurve, pintersection, ptangent;
double ulength, uangle, uradius, utangent, uchord, umidordinate, uexternal;
double pi;
double choice, choice2, given;

pi = 3.14159;

printf("Enter radius: ");
scanf("%lf",&radius);

printf("Enter angle: ");
scanf("%lf",&angle);

utangent = radius * (tan(angle/2)); 
uchord = 2*radius*(sin(angle/2));
umidordinate = radius - (radius*(cos(angle/2)));
//uexternal = radius * (sec(angle/2)) - radius;

printf("tangent = %lf\n",utangent);
printf("chord = %lf\n",uchord);
printf("ordinate = %lf\n",umidordinate);
//printf("%lf\n",uexternal);

getch();
return 0;
}

【问题讨论】:

  • 您使用了错误的格式说明符。 %lf 必须用于扫描double。 (不过,%f 应该用于 printf)。此外,检查 scanf 的返回值以检测错误。
  • 3.14159 远非双精度。使用M_PIboost::math::constants::pi

标签: c math trigonometry


【解决方案1】:

如果您在编译代码时出现警告(您绝对应该这样做),您可能会看到如下内容:

sintancos.c:15:13: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
scanf("%f", &angle);
       ~~   ^~~~~~
       %lf

按照警告消息的建议,通过将其重写为 scanf("%lf", &amp;angle); 来解决此问题。

我假设您需要重新计算从度数到弧度的输入,因为您要的是度数。当然,在再次输出之前,您需要将其改回度数。

通常在 C 中使用宏来完成,但我更喜欢函数。

double to_degrees(double rad)
{
  return rad * 180.0 / M_PI;
}
double to_radians(double deg)
{
  return deg * M_PI / 180.0;
}

M_PI 几乎总是在 math.h 中定义,比您的 pi 具有更高的精度。您还应该将输入和计算转移到它自己的函数中,这样更容易阅读和测试。

sec 不是标准的 C 函数,所以你必须自己定义它。它会是这样的:

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

double to_degrees(double rad)
{
  return rad * 180.0 / M_PI;
}

double to_radians(double deg)
{
  return deg * M_PI / 180.0;
}

double sec(double z_r)
{
  return 1 / cos(z_r);
}

int main(){

  double angle, radius, angle_r;
  double utangent, uchord, umidordinate, uexternal;


  //printf("Enter radius: ");
  //scanf("%lf",&radius);
  radius = 286;

  //printf("Enter angle: ");
  //scanf("%lf",&angle);
  angle = 36;

  angle_r = to_radians(angle);

  utangent = radius * (tan(angle_r/2)); 
  uchord = 2*radius*(sin(angle_r/2));
  umidordinate = radius - (radius*(cos(angle_r/2)));
  uexternal = radius * (sec(angle_r/2)) - radius;

  printf("\nResults:\n");
  printf("tangent = %lf\n",utangent);
  printf("chord = %lf\n",uchord);
  printf("ordinate = %lf\n",umidordinate);
  printf("external %lf\n",uexternal);

  return 0;
}

【讨论】:

  • 嗨,我编辑了我的问题,以便更容易理解,也缩短了我的代码