CPrimer Plus 5学习记录

C Primer Plus 5

一、运算符、表达式和语句

1、编程练习

(1)编写一条程序,把用分钟表示的时间换成用小时和分钟表示的时间。使用#define或者const创建一个表示60的符号常量或者const常量。通过while循环让用户重复输入值,直到小于等于0才停止循环。

#include<stdio.h>
#include<windows.h>
#define MIN_PER_HOU 60    //每小时有60min
int main(void)
{
   int hours,minutes,input;
   printf("Convert minutes to hours!\n");
   printf("Please input the number of minutes:\n");
   scanf("%d",&input);
   while(input>0)
  {
       hours = input/MIN_PER_HOU;
       minutes = input%MIN_PER_HOU;
       printf("Convert to %d hours and %d minutes!",hours,minutes);
       printf("Please continue input the number of minutes:\n");
       scanf("%d",&input);
  }
   printf("Program exit!\n");
   system("pause");
   return 0;    
}

(2)编写一个程序,提示用户输入一个整数,然后打印从该数到比该数大10的所有整数,打印各值之间用一个空格分开。

#include<stdio.h>
#include<windows.h>
int main(void)
{
   int counter,i=0;
   printf("Please input the number:\n");
   scanf("%d",&counter);
   while(i<=10)
  {
       printf("%d\n",counter);
       counter++;
       i++;
  }
   system("pause");
   return 0;
}

(3)编写一个程序,将天数转化为周数和天数

#include<stdio.h>
#include<windows.h>
#define WEEKS_PER_DAY 7
int main(void)
{
   int days,weeks,input;
   printf("Let's convert days to weeks!\n");
   printf("Please input the days:\n");
   scanf("%d",&input);
   while(input>0)
  {
       weeks = input/WEEKS_PER_DAY;
       days = input%WEEKS_PER_DAY;
       printf("%d days is equal to %d weeks and %d days!\n",input,weeks,days);
       printf("If you want to go on,please input another number:\n");
       scanf("%d",&input);
  }
   while(input<=0)
  {
       printf("Thanks to join the program!\n");
       break;
  }
   system("pause");
   return 0;
}

(4)编写一个程序,使用户输入一个double类型的数,并打印立方值。

#include<stdio.h>
#include<windows.h>
double cubic(double n);
int main(void)
{
   double input;
   printf("Enter the double datum to calc cubic:\n");
   scanf("%lf",&input);
   cubic(input);
   printf("program exit!\n");
   system("pause");
   return 0;
}
double cubic(double n)
{
   double t = n *n *n;
   printf("The %lg's cubic is %lg!\n",n,t);
   return t;
}

(5) 编写一个程序,自定义函数temperatures(),输入华氏温度,计算摄氏温度和开氏温度。并以小数点后两位精度显示三种温度。

#include<stdio.h>
#include<windows.h>
int Temperatures(double fah);
int main(void)
{
   double input;
   printf("This program convert fah to cel and kel.\n");
   printf("Enter a fah to start:\n");
   while(scanf("%lf",&input)==1)
  {
       Temperatures(input);
       printf("Enter the next fah(q to quit):\n");
  }
   printf("Done!\n");
   system("pause");
   return 0;
}
int Temperatures(double fah)
{
   const double F_TO_C = 32.0;
   const double C_TO_K = 273.16;
   double cel,kel;
   cel = 5.0/9.0*(fah-F_TO_C);
   kel = cel + C_TO_K;
   printf("%.2f.fah,equal %.2f celsius,and %.2f kel\n",fah,cel,kel);
   return 0;
}

 

 

上一篇:C Primer Plus 4学习记录


下一篇:《C++Primer(第5版)》第八章笔记