[C語言程序設計現代方法] 第1章 第2章 C語言概述和基本概念


教材:《C語言程序設計_現代方法 第2版》


C語言概述和基本概念

第1章 C語言概述

C語言的歷史

一些饒有余味的歷史節點:

  • 上世紀60年代、ThompsonBCPL語言的基礎上設計了B語言

  • 1971年、加入開發的RitchieB語言的基礎上設計了C語言

  • 1978年、K&R兩位編寫了第一本C語言教程The C Programming Lauguage,這一版的標准叫做經典C,后來出的第二本里參考了ANSI里的標准

  • 1983年、美國國家標准協會(ANSI)開始制定C語言標准;1990年,國際標准化組織(ISO)通過此項標准,后來ANSI C這一標准叫做標准C

  • C語言的發展:Concurrent C 和 Objective C 以及C++語言

    • C++比C語言難學,因此最好先精通C++語言
    • 使用C++語言時,需要避免C語言的編程習慣

C語言的優缺點

C語言的自身特性

  • C語言是一種低級語言。C語言的設計思想是更好的操控底層,因此C語言是較其他高級語言來說比較底層的一門語言。
  • C語言是一種小型語言。與其他語言相比,C語言的語法是相對較少的。
  • C語言是一種包容性語言。C語言提供了更廣闊的自由度。

C語言的優點

  • 高效性。
  • 可移植性。
  • 功能強大。
  • 靈活性。
  • 標准庫。
  • 與UNIX系統的集成。

C語言的缺點

  • C程序可能會漏洞百出。
  • C程序可能會難以理解。
  • C程序可能會難以修改。

高效的使用C語言

  • 學習如何規避C語言的缺陷。
  • 使用軟件工具使程序更加可靠。
  • 利用現有的代碼庫。
  • 采用一套切合實際的編碼規范。
  • 避免"投機取巧"和極度復雜的代碼
  • 使用標准C,少用經典C
  • 避免不可移植性。

第2章 C語言基本概念

預處理指令、函數、變量、語句

程序編譯和鏈接

當寫完一個程序后,例如以下程序

#include<stdio.h>

main()
{
    printf("to c,or not to c,that is the question")
}

要經歷以下過程:

預處理->編譯->鏈接

  • 預處理:處理#開頭的指令,可以給程序添加內容,也可以修改程序
  • 編譯:將程序翻譯成機器指令(目標代碼object code)
  • 鏈接:將所有相關程序的目標代碼整合在一起。

gcc編譯器可以通過指令進行編譯:gcc -o fun fun.c
也可以使用一些集成開發環境IDE進行開發。

簡單程序的通用形式

指令

預處理器執行的命令稱為指令

函數

有輸入有返回值的特定語句塊就叫做函數

語句

語言是程序運行時執行的命令。

注釋

/**/組成的注釋

  • 注釋可以出現在程序的任意位置。
  • 注釋可以占用多行。
  • 可以同代碼放在一行。
  • 防止注釋缺失或者注釋嵌套。

變量和賦值

類型

intfloat

  • int類型又叫做整型。取值范圍-32768 ~ 32767
  • float類型又叫浮點型。做運算時比int慢,同時數值不精確(四舍五入)。

聲明

使用變量之前需要對其進行聲明。例如 int height;

如果光聲明不初始化,變量的值 是不確定的。

賦值

變量 通過賦值的方式獲得值。height = 8;

顯示變量的值

使用庫函數中的printf來 打印變量,例如 printf("profit:$%.2f\n",profit);

  • %d用於int型變量
  • %f用於float型變量。默認情況下,%f顯示 小數點后六位的數據,如果需要指定小數點后 n位,用%.nf表示。

初始化

在聲明的時候即對變量賦值,就是對變量進行初始化 。例如int height = 8;

顯示表達式的值

printf也可以顯示任意表達式的值。

讀入輸入

scanfprintf差不多。

需要提前定義一個變量。scanf("%f",&x)

定義常量

常量(constant)是程序執行過程中固定不變的量。

  • 常量通常采用 宏定義的 方式命名。
  • 命名規范是全部用大寫,_連接

標識符

對變量 ,函數,宏及其他實體命名的名字叫做 標識符

  • 標識符必須以字母或者下划線_開頭。
  • 標識符區分大小寫。

關鍵字

關鍵字對編譯器來說有特殊意義 ,因此不能拿來作為標識符使用。

C語言程序的布局

  • 語句可以划分在任意多行內,如果過長則要壓縮在一行內。
  • 記號之間的空格應該便於肉眼區別記號。
  • 縮進有 助於識別程序嵌套。
  • 空行可以把程序分成邏輯單元。

exercise & project

exercise

2.01

Create and run Kernighan and Ritchie's famous "hello, world" program:

#include <stdio.h>

int main(void)
{
    printf("hello, world\n");
}

Do you get a warning message from the compiler? If so, what's needed to make it go away?

Solution:

Compiling the program produced no errors using gcc version 7.2.0. Here is the complete output of run commands:

$ gcc 1.c -o 1 -Wall -W -pedantic -std=c99
(no output, no warnings or errors)

$ gcc 1.c -o 1 -Wall -W -pedantic -std=c89
1.c: in function 'main':
1.c:5:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

This warning can be fixed by amending return 0;

#include <stdio.h>

int main(void) {
    printf("hello, world\n");
    return 0;
}

$ gcc 1b.c -o 1b -Wall -W -pedantic -std=c89
(no output, no warnings or errors)
2.02

Consider the following program:

#include <stdio.h>

int main(void)
{
    printf("Parkinson's Law:\nWork expands so as to ");
    printf("fill the time\n");
    printf("available for its completion.\n");
    return 0;
}

(a) Identify the directives and statements in this program.
(b) What output does the program produce?

Solution

(a)

The only directive in the program is #include <stdio.h> in line 1. The statements are the lines 5-8: the printf() statements and the return statement.

(b)

The program produces the following:

Parkinson's Law:
Work expands so as to fill the time
available for its completion.
2.03

Condense the dweight.c program by (1) replacing the assignments to height,
length, and width with initializers and (2) removing the weight variable,
instead calculating (volume + 165) / 166 within the last printf.

Solution

#include <stdio.h>

int main(void) {

    int height = 8,
        length = 12,
        width = 10,
        volume = height * length * width;

    printf("Dimensions: %dx%dx%d\n", length, width, height);
    printf("Volume (cbic inches): %d\n", volume);
    printf("Dimensional weight (pounds): %d\n", (volume + 165) / 166);

    return 0;
}

2.04

Write a program that declares several int and float variables--without
initializing them--and then prints their values. Is there any pattern to the
values? (Usually there isn't.)

Solution

#include <stdio.h>

int main(void) {

    int a, b, c, d, e;
    float f, g, h, i, j;
    
    printf("%d\n%d\n%d\n%d\n%d\n%f\n%f\n%f\n%f\n%f\n", 
           a, b, c, d, e, f, g, h, i, j);

    return 0;
}

There is no pattern for the first few integers produced, however, upon repeated
compilations and repeated tests, the last two integers and all floats are
usually 0 or 0.000000, with occasional deviation to "random" garbage values.

2.05

Which of the following are not legal C identifiers?

(a) 100_bottles
(b) _100_bottles
(c) one_hundred_bottles
(d) bottles_by_the_hundred

Solution

(a) is not a legal identifier, because identifiers must start with a letter or
underscore.

2.06

Why is it not a good idea for an identifier to contain more than one adjacent
underscore (as in current___balance, for example)?

Solution

An identifier with multiple consecutive underscores are difficult to read. It is
hard to determine exactly how many underscore characters there are in the
identifier, and the use of multiple underscores serves no purpose.

2.07

Which of the following are keywords in C?

(a) `for`  
(b) `If`  
(c) `main`  
(d) `printf`  
(e) `while`

Solution

(a) and (e) are keywords. (b) would be a keyword if If was written as if.

2.08

How many tokens are there in the following statemnt?

answer=(3*q-p*p)/3;

Solution

There are thirteen tokens in the statement, six of which are non-unique.

2.09

Insert spaces between the tokens in Exercise 8 to make the statement easier to
read.

Solution

answer = (3 * q - p * p) / 3;
2.10

In the dweight.c program (Section 2.4), which spaces are essential?

Solution

Below is the complete dweight.c program, as written in Section 2.4:

/* Computes the dimensional weight of a 12" x 10" x 8" box */

#include <stdio.h>

int main(void)
{
    int height, length, width, volume, weight;

    height = 8;
    length = 12;
    width = 10;
    volume = height * length * width;
    weight = (volume + 165) / 166;

    printf("Dimensions: %dx%dx%d\n", length, width, height);
    printf("Volume (cubic inches): %d\n", volume);
    printf("Dimensional weight (pounds): %d\n", weight);

    return 0;
}

The only spaces which are necessary are the line break in the #include
directive and its space between #include and <stdio.h> as well as the space
between return and 0.

practice

2.01

Write a program that uses printf to display the following picture on the
screen:

       *
      *
     *
*   *
 * *
  *

Solution

#include <stdio.h>

int main(void) {
    
    printf("       *\n");
    printf("      * \n");
    printf("     *  \n");
    printf("*   *   \n");
    printf(" * *    \n");
    printf("  *     \n");

    return 0;
}

2.02

Write a program that computes the volume of a sphere with a 10-meter radius,
using the formula v = 4/3πr³. Write the fraction 4/3 as 4.0f/3.0f. (Try
writing it as 4/3. What happens?) Hint: C doesn't have an exponentiation
operator, so you'll need to multiply r by itself twice to compute r³.

Solution

#include <stdio.h>

int main(void) {

    printf("Sphere volume: %.2f cubic meters\n", 4.0f/3.0f * 3.14f * 1000);
    return 0;
}

Writing the fraction in integer form will result in a integer rounding error,
returning 1.

2.03

Modify the program of Programming Project 2 so that it prompts the user to enter
the radius of the sphere.

Solution

#include <stdio.h>

int main(void) {

    int r = 0;

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

    printf("\nSphere volume: %.2f cubic meters\n",
           4.0f/3.0f * 3.14f * r * r * r);
    return 0;
}

2.04

Write a program that asks the user to enter a dollars-and-cents amount, then
displays the amount with a 5% tax added:

Enter an amount: 100.00
With tax added: $105.00

Solution

#include <stdio.h>

int main(void) {

    float money = 0.0f;
    printf("Enter an amount: ");
    scanf("%f", &money);
    printf("With tax added: $%.2f\n", money * 1.05f);

    return 0;
}

2.05

Write a program that asks the user to enter a value for x and then displays the
value of the following polynomial:

3x5 + 2x4 - 5x3 - x2 + 7x - 6

Hint: C doesn't have an exponentiation operator, so you'll need to multiply x
by itself repeatedly in order to compute the powers of x. (For example, x * x * x is x cubed.)

Solution

#include <stdio.h>

int main(void) {

    int x = 0;

    printf("Enter value for x: ");
    scanf("%d", &x);
    printf("Result: %d\n",
           (3 * x * x * x * x * x) + (2 * x * x * x * x) - (5 * x * x * x)
           - (x * x) + (7 * x) - 6);

    return 0;
}

2.06

Modify the program of Programming Project 5 so that the polynomial is evaluated
using the following formula:

((((3x + 2)x-5)x-1)x+7)x-6

Note that the modified program performs fewer multiplications. This technique
for evaluating polynomials is known as Horner's Rule.

Solution

#include <stdio.h>

int main(void) {

    int x = 0;

    printf("Enter value for x: ");
    scanf("%d", &x);
    printf("Result: %d\n",
           ((((3 * x + 2) * x - 5) * x - 1) * x + 7) * x - 6);

    return 0;
}

2.07

Write a program that asks the user to enter a U.S. dollar amount and then shows
how to pay that amount using the smallest number of $20, $10, $5 and $1 bills:

Enter a dollar amount: 93

$20 bills: 4
$10 bills: 1
 $5 bills: 0
 $1 bills: 3

Hint: Divide the amount by 20 to determine the number of $20 bills needed, and
then reduce the amount by the total value of the $20 bills. Repeat for the
other bill sizes. Be sure to use integer values throughout, not floating-point
numbers.

Solution

#include <stdio.h>

int main(void) {

    int money = 0;

    printf("Enter a dollar amount: ");
    scanf("%d", &money);

    printf("$20 bills: %d\n", money/20);
    money -= 20 * (money/20);

    printf("$10 bills: %d\n", money/10);
    money -= 10 * (money/10);

    printf(" $5 bills: %d\n", money/5);
    money -= 5 * (money/5);

    printf(" $1 bills: %d\n", money);

    return 0;
}

2.08

Write a program that calculates the remaining balance on a loan after the first,
second, and third monthly payments:

Enter amount of loan: 20000.00
Enter interest rate: 6.0
Enter monthly payment: 386.66

Balance remaining after first payment: $19713.34
Balance remaining after second payment: $19425.25
Balance remaining after third payment: $19135.71

Display each balance with two digits after the decimal point. Hint: Each
month, the balance is decreased by the amount of the payment, but increased by
the balance times the monthly interest rate. To find the monthly interest rate,
convert the interest rate entered by the user to a percentage and divide it by

Solution

#include <stdio.h>

int main(void) {

    float loan = 0.0f,
          rate = 0.0f,
          payment = 0.0f;

    printf("Enter amount of loan: ");
    scanf("%f", &loan);

    printf("Enter interest rate: ");
    scanf("%f", &rate);

    printf("Enter monthly payment: ");
    scanf("%f", &payment);


    loan = loan - payment + (loan * rate / 100.0 / 12.0);
    printf("Balance remaining after first payment: $%.2f\n", loan);

    
    loan = loan - payment + (loan * rate / 100.0 / 12.0);
    printf("Balance remaining after second payment: $%.2f\n", loan); 

    loan = loan - payment + (loan * rate / 100.0 / 12.0);
    printf("Balance remaining after third payment: $%.2f\n", loan);

    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM