C prime plus Chapter 8 (Character Control) Programming Exercises -- Fifth Edition

C prime plus Chapter 8 (Character Control) Programming Exercises – Fifth Edition

The c language programming exercises are all written code records or study notes when I study. If there is anything inappropriate, please correct me and be grateful (of course, there may be other programming design solutions for the question type, such as using custom functions, etc., because I am in The basics of the drill are not covered, just for the record).



1. Design a program that counts the number of characters from the input to the end of the file.

#include<stdio.h>

int main(void)
{
    int i;
    char ch;
    for(i = 0; (ch = getchar()) != EOF; i++);
    printf("COUNT = %d \n", i);
    printf("%d\n", ch);
    return 0;
}


2. Write a program that reads input as a stream of characters until EOF is encountered. Tell the program to print each input character and its ASCII-encoded decimal value. Note that characters preceding the space character in an ASCII sequence are nonprinting characters and require special treatment. If the nonprinting character is a newline or tab, print \n or \t in intervals. Otherwise, control character symbols are used. For example, l in ASCII is Ctrl+A and can be displayed as AA. Note that the A ASCII value is the value of Ctrl+A plus 64. Similar relationships are maintained for other nonprinting characters. Print 10 pairs of values ​​per line, except that a new line is started each time a newline character is encountered.

#include<stdio.h>

int main(void)
{
    char  ch;
    int i;

    for(i = 1; (ch = getchar()) != EOF; i++) {
        if(ch >= ' ' || ch == '\n' || ch == '\t')
            printf("%-5c", ch);
        else
            printf("%-4c", ch + 64);
        printf("%-5d", ch);
        if(i % 10 == 0)
            printf("\n");
    }
    return 0;
}


3. Write a program that reads input as a stream of characters until EOF is encountered. Make it report the number of uppercase and lowercase letters in the input. The lowercase letters are assumed to have consecutive numerical values, as are the uppercase letters. Or you can use the appropriate functions from the ctypc,h library for case sensitivity.

#include<stdio.h>
#include<ctype.h>

int main(void)
{
    char ch;
    int l = 0, u = 0;

    printf("Please input some characters:\n");
    while((ch = getchar()) != EOF) {
        if(islower(ch))
            l++;
        if(isupper(ch))
            u++;
    }
    printf("\nlower letter = %d,\nupper letter = %d.\n", l, u);

    return 0;
}


4. Write a program that reads input as a stream of characters until EOF is encountered. Let it report the average number of letters per word. Do not count whitespace characters as letters in words. Actually, punctuation shouldn't be counted either, but don't have to think about that for now (if you want to do better, consider the ispunct() function from the ctype.h family).

#include<stdio.h>
#include<ctype.h>
#include<stdbool.h>

int main(void)
{
    char ch;
    int word = 0, i = 0;
    bool inword = false;

    while((ch = getchar()) != EOF) {
        if(!ispunct(ch) && !isspace(ch))
            i++;
        if(isspace(ch) && !inword) {
            inword = true;
            word++;
        }
        if(!isspace(ch) && inword)
            inword = false;
    }
    printf("\ni: %d\nword: %d\naverage: i/word = %f\n", i, word, (float)i / (float)word);
    return 0;
}


5. Modify the guessing program in Listing 8,4 to use a smarter guessing strategy. For example, the program initially guesses 50 and asks the user whether the guess is large, small, or correct. If the guess is small, let the next guess be the median of 50 and 100, which is 75. If 75 is large, the next guess is the median of 75 and 50, and so on. Using this binary search strategy, the program will quickly get the correct answer, at least if the user is not deceived.

#include<stdio.h>

int main(void)
{
    int guess, max, min;
    min = 0, max = 100;
    char res; /* res-response */

    printf("Pick an integer from 1 to 100. I will try to guess ");
    printf("it. \nRespond with a b if my guess is big and with ");
    printf("\nan l if it is little.\n");
    printf("Also, Respond a y if it is right.\n");
    printf("Uh...is your number %d?\n", guess = (max + min)/2);

    while((res = getchar()) != 'y') /* 获取用户响应并和y比较 */ {
        if(res == 'b') {
            max = guess - 1;
            printf("Well, then, is it %d?\n", guess = (max + min)/2);
        }

        if(res == 'l') {
        min = guess + 1;
            printf("Well, then, is it %d?\n", guess = (max + min)/2);
        }

        else
            printf("Sorry, I understand only y or n.\n");

        while(getchar() != '\n');
    }

    printf("I knew I could do it!\n");

    return 0;
}


6. Modify the get_first() function in Listing 8.8 to return the first non-whitespace character encountered. Test the h function in a simple program.

#include<stdio.h>
#include<ctype.h>

char get_first(void);

int main(void)
{
    char ch;

    while((ch = getchar()) != EOF) {
        putchar(ch);
    }

    return 0;
}

char get_first(void)
{
    int ch;

    while(isspace(ch = getchar()));

    while(getchar() != '\n');
    return ch;
}


7. Modify Exercise 8 in Chapter 7 so that menu options are labeled with characters instead of numbers.

#include<stdio.h>
#define TIME 40             //正常工作时间
#define ADD 1.5             //加班的折算时间倍数
#define L1 300              //工资额度1
#define RATE1 0.15          //L1的税率
#define L2 150              //工资额度2
#define RATE2 0.20          //L2的税率
#define RATE3 0.25          //余下工资额度的税率
int main(void)
{
    double h, g, t, BASIC;
    int d;
    char n;
    //h-hours,g-gross,t-tax,d-data

    for(d = 0; d < 69; d++)
        printf("*");
    printf("\n\n");

    printf("Enter the number corresponding to the desired pay rate or action:\n");
    printf("1) $8.75/hr\t\t\t2) $9.33/hr\n");
    printf("3) $10.00/hr\t\t\t4) $11.20/hr\n");
    printf("5) quit\n\n");

    for(d = 0; d < 69; d++)
        printf("*");
    printf("\n");
    n = getchar();
    while(getchar() != '\n' );
    while(1) {
        while( n < '1' || n > '5') {
            printf("error,it's wrong number,please input again!(1-5):\n");
            n = getchar();
        }
        switch(n) {
            case '1': BASIC = 8.75;
                break;
            case '2': BASIC = 9.33;
                break;
            case '3': BASIC = 10.00;
                break;
            case '4': BASIC = 11.20;
                break;
            case '5': printf("quit!\n");
                return 0;
        }

        printf("input the work hours of a week:\n");
        scanf("%lf", &h);
        if(h > 40)
            h = 40 + (h - 40) * ADD;
        g = h * BASIC;
        if(g <= L1)
            t = g * RATE1;
        else if(g <= L2)
            t = g * RATE1 + (g - L1) * RATE2;
        else
            t = g * RATE1 + (g - L1) * RATE2 + (g - L1 - L2) * RATE3;
        printf("gross income = %lf\n", g);
        printf("tax = %lf\n", t);
        printf("net income = %lf\n", g - t);
        printf("Please input your selection(1~4) again!(type 5 to quit).\n");
        while(getchar() != '\n');
        n = getchar();
    }
    return 0;
}


8. Write a program that displays a menu that gives you options for addition, subtraction, multiplication, or division. After getting your choice, the program requests two numbers and then performs the action of your choice. The program should only accept the menu options it offers. It should use a number of type float, and should allow the user to re-enter a number if it fails to enter. In the case of division, if the user enters 0 as the second number, the program should prompt the user to enter a new value. A typical program run should look like this:

8.8

#include<stdio.h>
#include<ctype.h>

float get_float(void);
char get_first(void);


int main(void)
{
    char se ;       /* select */
    float n1, n2;   /* number1, number2 */

    while(1) {
        printf("Enter the operation of your choice:\n");
        printf("a. add\t\t\ts. subtract\n");
        printf("m. multiply\t\td. divide\n");
        printf("q. quit\n");
        se = get_first();

        if(se != 'a' && se != 's' && se != 'm' && se != 'd') {
            printf("Bye!.\n");
            break;
        }

        printf("Enter first number:");
        n1 = get_float();
        printf("Enter second number:");
        n2 = get_float();

        while(se == 'd' && n2 == 0) {
            printf("Enter a number other than 0:");
            n2 = get_float();
        }
        switch(se) {
            case 'a': printf("%.2f + %.2f = %.2f\n", n1, n2, n1 + n2);
                    break;
            case 's': printf("%.2f - %.2f = %.2f\n", n1, n2, n1 - n2);
                    break;
            case 'm': printf("%.2f * %.2f = %.2f\n", n1, n2, n1 * n2);
                    break;
            case 'd': printf("%.2f / %.2f = %.2f\n", n1, n2, n1 / n2);
                    break;
            default:
                    break;
    }

    return 0;
}

float get_float(void)       /* 得到一个合适的浮点数 */
{
    float n;
    char str[40];
    while(scanf("%f", &n) != 1) {
        fgets(str, 40, stdin);
        printf("%s is not a number.\n", str);
        printf("Please enter a number, such as 3.2 -1.34E5, or 2:");
    }
    while(getchar() != '\n');

    return n;
}

char get_first(void)  /* 只获取字符串首字符 */
{
    int ch;

    while(isspace(ch = getchar()));
    while(getchar() != '\n');
    return ch;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324778847&siteId=291194637