4-1
#include <stdio.h>
int main(void)
{
char xing[30],ming[30];
scanf("%s%s",ming,xing);
printf("%s,%s\n",ming,xing);
return 0;
}
4-2
#include <stdio.h>
#include <string.h>
int main(void)
{
int a,b;
char xing[30],ming[30];
scanf("%s%s",ming,xing);
a = strlen(ming) + 3;
b = strlen(xing) + 3;
printf("\"%s\" \"%s\"\n",ming,xing);
printf("\"%20s\" \"%20s\"\n",ming,xing);
printf("\"%-20s\" \"%-20s\"\n",ming,xing);
printf("\"%*s\" \"%*s\"\n",a,ming,b,xing);
return 0;
}
4-3
#include <stdio.h>
int main (void)
{
float a;
scanf("%f",&a);
printf("%f\n",a);
printf("%e\n",a);
return 0;
}
4-4
#include <stdio.h>
int main(void)
{
char name[40];
float height;
scanf("%f",&height);
scanf("%s",name);
printf("%s,you are %f feet tall\n",name,height / 100);
return 0;
}
4-5
#include <stdio.h>
int main(void)
{
float speed, size;
printf("Please enter net speed(Mb/s): ");
scanf("%f", &speed);
printf("Please enter file size(MB): ");
scanf("%f", &size);
printf("At %.2f megabits per second, ", speed);
printf("a file of %.2f megabytes\n", size);
printf("downloads in %.2f seconds.\n", size * 8 / speed);
return 0;
}
4-6
#include <stdio.h>
#include <string.h>
int main(void)
{
int x, y;
char fname[20], lname[20];
printf("Please enter your first name: ");
scanf("%19s", fname);
printf("Please enter your last name: ");
scanf("%19s", lname);
x = strlen(fname);
y = strlen(lname);
printf("%s %s\n", fname, lname);
printf("%*d %*d\n", x, x, y, y);
printf("%s %s\n", fname, lname);
printf("%-*d %-*d\n", x, x, y, y);
return 0;
}
4-7
#include <stdio.h>
#include <float.h>
int main(void)
{
float f_value = 1.0 / 3.0;
double d_value = 1.0 / 3.0;
printf("1.0 / 3.0 display 6 decimal places:\n");
printf("f_value = %.6f\nd_value = %.6lf\n", f_value, d_value);
printf("\n1.0 / 3.0 display 12 decimal places:\n");
printf("f_value = %.12f\nd_value = %.12lf\n", f_value, d_value);
printf("\n1.0 / 3.0 display 16 decimal places:\n");
printf("f_value = %.16f\nd_value = %.16lf\n", f_value, d_value);
printf("\nfloat and double maximum precious digits:\n");
printf("FLT_DIG = %d, DBL_DIG = %d\n", FLT_DIG, DBL_DIG);
//4.8-7书上问答: 不一致, 因为float精确度是6位, 而double是15位, 所以在超过精确度位数后会有差异
return 0;
}
4-8
#include <stdio.h>
#define GALLON_TO_LITRE 3.785
#define MILE_TO_KM 1.609
int main(void)
{
double range, oil;
printf("Please input the range you traveled(in mile): ");
scanf("%lf", &range);
printf("Please input the oil you spend(in gallon): ");
scanf("%lf", &oil);
printf("Fuel consumptions:\n");
printf("In USA, your oil wear is %.1f mile / gallon.\n", range / oil);
printf("In Europe, your oil wear is ");
printf("%.1f litre / 100km.\n", 100.0 * (oil * GALLON_TO_LITRE) / (range * MILE_TO_KM));
return 0;
}