天天看點

C Primer Plus 第6版 第3章 程式設計練習

1.編寫程式檢視系統如何處理整數上溢和浮點數上溢和下溢情況。

#include<stdio.h>
int main(void)
{

  int int_a = -1;
  float float_a = -1.0;
  for (int i = 1; i <= 128; i++)
  {
    int_a *= 2;
    float_a *= 2;
    printf("2^%d = %d\t\t\t 2^ %d = %f\n", i, int_a, i, float_a);
  }


  getchar(); getchar(); //在VS中讓視窗停留
  return 0;
}      

2.提示輸入一個ASCII碼,然後列印對應的字元。

#include<stdio.h>
int main(void)
{
  int ascii_n;
  char ascii_c;
  printf("請輸入一個ASCII碼:");
  scanf_s("%d", &ascii_n);
  ascii_c = ascii_n;
  printf("%c", ascii_c);
  getchar(); getchar(); //在VS中讓視窗停留
  return 0;
}      

 3.發出響鈴,然後列印一串文本

#include<stdio.h>
int main(void)
{

  printf("\a");
  printf("Startled by the sudden sound, Sally shouted,\n");
  printf("\"By the Great Pumpkin, what was that! \"");
  getchar(); getchar(); //在VS中讓視窗停留
  return 0;
}      

4.讀取一個浮點數,以小數和指數形式列印 

#include<stdio.h>
int main(void)
{
  float float_n;
  printf("Enter a floating-point value: ");
  scanf_s("%f", &float_n);
  printf("fixed-point notation:%f\n",float_n);  //小數點形式
  printf("exponential notation:%e\n", float_n); // 指數形式
  printf("p notation: %a\n" ,float_n);          //十六進制
  getchar(); getchar(); //在VS中讓視窗停留
  return 0;
}      

5.一年大概有3.156 x 10^7 秒。 輸入年齡,轉換成對應的秒。

#include<stdio.h>
int main(void)
{
  int age;
  const float secondsOfAYear = 3.156e7;
  printf("輸入年齡: ");
  scanf_s("%d", &age);
  printf("相當于 %f 秒\n" ,secondsOfAYear*age);        
  getchar(); getchar(); //在VS中讓視窗停留
  return 0;
}      

6.   1個水分子品質為 3 * 10 ^-23 g , 1 誇脫的水是950g.輸入誇脫數,轉換成水分子數,

#include<stdio.h>
int main(void)
{
  float quart;
  const float water = 3.0e23;
  const int aquart = 950;
  printf("輸入水的誇脫數: ");
  scanf_s("%f", &quart);
  printf("相當于 %f 個水分子\n" ,quart*aquart*water);        
  getchar(); getchar(); //在VS中讓視窗停留
  return 0;
}      

 7.  1英寸相當于2.54厘米,輸入英寸轉換厘米。

#include<stdio.h>
int main(void)
{
  const float inchToCm = 2.54;
  float inch;
  printf("請輸入英寸:");
  scanf_s("%f", &inch);
  printf(" %f英寸相當于%f厘米", inch, inch*2.54);
  getchar(); getchar(); //在VS中讓視窗停留
  return 0;
}      

8.機關轉換

#include<stdio.h>
int main(void)
{
  float cup;
  printf("輸入杯數:");
  scanf_s("%f", &cup);
  printf("相當于%f品脫\n%f盎司\n%f大湯勺\n%f茶勺", cup / 2,8*cup,16*cup,48*cup);

  getchar(); getchar(); //在VS中讓視窗停留
  return 0;
}