c - 无法使定义的数字正常工作



该程序假设运行并打印出表面积,卫星数量和与太阳的距离。我不知道如何让定义的数字在程序中工作。任何提示都会有所帮助。谢谢

#include <stdio.h>
#include <stdlib.h>
#define Mercury_diameter 4879
#define Venus_diameter 12104
#define Earth_diameter 12756
#define Mars_diameter 6792
#define Mercury_distance 57.9
#define Venus_distance 108.2
#define Earth_distance 149.6
#define Mars_distance 227.9
#define Mercury_moons 0
#define Venus_moons 0
#define Earth_moons 1
#define Mars_moons 2
#define PI 3.1415926535
int main()
{
char planet;
printf("Please enter the first letter of the planet whose information you'd        like to see.n");
printf("Use lower-case letters. Use 'a' for Mars Please! n");
scanf("%c", &planet);
float m_rad = Mercury_diameter/2.;
float v_rad = Venus_diameter/2.;
float e_rad = Earth_diameter/2.;
float a_rad = Mars_diameter/2.;

float m_surf = 4 * PI * m_rad * m_rad;
float v_surf = 4 * PI * v_rad * v_rad;
float e_surf = 4 * PI * e_rad * e_rad;
float a_surf = 4 * PI * a_rad * a_rad;

switch (planet)
{
   case 'm':
m_surf = 4. * PI * m_rad * m_rad;
printf("The surface area of Mercury = %f n", m_surf);
printf("Mercury has Mercury_moons moons. n");
printf("The distance between Mercury and the sun is Mercury_distance n");
break;
  case 'v':
v_surf = 4. * PI * v_rad * v_rad;
printf("The surface area of Venus = %f n", v_surf);
printf("Venus has Venus_moons moons. n");
printf("The distance between Venus and the Sun is Venus_distance n");
break;
  case'e':
e_surf = 4. * PI * e_rad * e_rad;
printf("The surface area of Earth = %f n", e_surf);
printf("Earth has Earth_moons moons. n");
printf("The distance between Earth and the Sun is Earth_distance n");
break;
  case 'a':
a_surf = 4. * PI * a_rad * a_rad;
printf("The surface area of Mars = %f n", a_surf);
printf("Mars has Mars_moons moons. n");
printf("The distance between Mars and the Sun is Mars_distance n");
break;
  default:
printf("You have entered an invalid entry!");
}
return 0;
}

问题是 #defines 不会在字符串中被替换。试着为月亮做这样的事情:

printf("Mars has %d moons. n", Mars_moons);

不会在字符串中展开。你可以这样做 - 写

printf("The distance between Mercury and the sun is %fn",Mercury_distance);

另请参阅此问题如何在 printf 函数中使用宏。

最新更新