Modern Design Methods of C Language Programming_Chapter 6 Code, Practice Questions and Answers to Programming Questions

the code

6.1 The square.c
program displays the square table
Now write a program to display the square table. First, the program prompts the user to input a number, and then displays the output of rows, each row contains a number from 1 to n and its square value.
This program prints a table of squares.
Enter number of entries in table: 5
1 1
2 4
3 9
4 16
5 25
Store the desired number of squares in the variable n. The program needs to use a loop to repeatedly display the number i and its square value, and the loop starts when i is equal to 1. If i is less than or equal to n, the loop will repeat. What needs to be guaranteed is that the value of i is incremented by 1 each time the loop is executed. Loops can be written using the while statement. (Frankly, there aren't many other options right now, since the while statement is the only type of loop we've mastered so far.) Here's the finished program.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
    
    
	int n, i;

	printf("This program prints a table of squares.\n");
	printf("Enter number of entries in table: ");
	scanf("%d", &n);

	i = 1;
	while (i <= n) {
    
    
		printf("%10d%10d\n", i, i * i);
		i++;
	}

	return 0;
}

Notice how the program square.c arranges the output neatly into two columns. The trick is to use a conversion specification like %10d instead of %d, and take advantage of the property of the printf function to right-align the output within the specified width.

6.1 sum.c
program summation
In the following example using the while statement, we have written a program to sum the integer series input by the user. Here's what the user sees:
This program sums a series of integers.
Enter integers (0 to terminate): 8 23 71 5 0
The sum is: 107
Clearly, the program needs a loop to read in the numbers (using scanf function) and accumulate them. Use n to denote the number currently read in, and sum to denote the sum of all previously read in numbers, the following program is obtained:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
    
    
	int n, sum = 0;

	printf("This program sums a series of integer.\n");
	printf("Enter integers (0 to terminate) : ");
	
	scanf("%d", &n);
	while (n != 0) {
    
    
		sum += n;
		scanf("%d", &n);
	}

	printf("The sum is: %d\n", sum);

	return 0;
}

Note that the condition n != 0 is evaluated immediately after the number is read, so that the loop can be terminated as soon as possible. In addition, two identical scanf function calls are used in the program, which is often difficult to avoid when using a while loop.

6.2 The numdigit.c
program calculates the number of digits in an integer.
Although the while statement in a C program occurs far more than the do statement, the latter is very convenient for loops that need to be executed at least once. To illustrate this point, now write a program to calculate the number of digits of the integer entered by the user:
Enter a nonnegative integer: 60
The number has 2 digit(s).
The method is to repeatedly divide the input integer by 10 until the result becomes 0 to stop ; The number of divisions is the required number of digits. Since it's not known exactly how many division operations are needed to reach 0, it's clear that the program needs some kind of loop. But should I use the while statement or the do statement? A do statement is obviously more appropriate, since every integer (including 0) has at least one digit. Below is the procedure.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
    
    
	int digits = 0, n;

	printf("Enter a nonnegative integer: ");
	scanf("%d", &n);
	
	do {
    
    
		n = n / 10;
		digits++;
	} while (n > 0);
	
	printf("The number has %d digit(s).\n", digits);

	return 0;
}

To show that the do statement is the right choice, let's observe what happens if we replace the do loop with a similar while loop:

while (n > 0) {
    
    
	n /= 10;
	digits++;
}

If the initial value of n is 0, the above loop will not execute at all, and the program will print
The number has 0 digit(s).

6.3 square2.c
The program square.c (➤ Section 6.1) can be improved by converting the while loop into a for loop.

/* Prints a table of squares using a for statement */
#include <stdio.h>
int main(void)
{
    
    
	int i, n;
	printf("This program prints a table of squares.\n");
	printf("Enter number of entries in table: ");
	scanf("%d", &n);
	for (i = 1; i <= n; i++)
		printf("%10d%10d\n", i, i * i);
	return 0;
}

Use this program to illustrate an important point about the for statement: C places no restrictions on the three expressions that control the behavior of the loop. Although these expressions typically initialize, evaluate, and update the same variable, there is no requirement that they be related in any way. Take a look at another version of the same program.
square3.c

/* Prints a table of squares using an odd method */
#include <stdio.h>
int main(void)
{
    
    
	int i, n, odd, square;
	
	printf("This program prints a table of squares.\n");
	printf("Enter number of entries in table: ");
	scanf("%d", &n);
	
	i = 1;
	odd = 3;
	for (square = 1; i <= n; odd += 2) {
    
    
		printf("%10d%10d\n", i, square);
		++i;
		square += odd;
	}
	
	return 0;
}

The for statement in this program initializes one variable (square), evaluates another variable (i), and increments a third variable (odd). The variable i is the number to be squared, the variable square is the squared value of variable i, and the variable odd is an odd number that needs to be added to the current squared value to obtain the next squared value (allowing the Computes consecutive squared values).
The great flexibility of the for statement is sometimes very useful. Later we will find that the for statement is very useful when dealing with linked lists (➤ Section 17.5). However, the for statement is easy to misuse, so don't go overboard. If you rearrange the contents of the program square3.c, you can clearly show that the loop is controlled by the variable i, so the for loop in the program is much clearer.

6.4 Checking.c
Program Book Settlement
Many simple interactive programs are menu-based: they show the user a list of commands to choose from; once the user selects a command, the program performs the corresponding operation and then prompts the user for the One command; this process continues until the user selects the "Exit" or "Stop" command. The heart of such programs is obviously the loop. There will be statements inside the loop that prompt the user to enter a command, read the command, and then determine the action to perform:

for  ( ;  ; ) {
    
    
	提示用户录入命令;
	读入命令;
	执行命令;
}

Executing this command would require a switch statement (or cascading if statements):

for  ( ;  ; ) {
    
    
	提示用户录入命令;
	读入命令;
	switch(命令){
    
    
		case 命令1:执行操作1; break;
		case 命令2:执行操作2; break;
		.
		.
		.
		case 命令n:执行操作n; break;
		default: 显示错误消息; break;
	}
}

To illustrate this format, develop a program that maintains ledger balances. The program will provide the user with a menu of options: clear the account balance, deposit money into the account, withdraw money from the account, display the current balance, and exit the program. The options are represented by integers 0, 1, 2, 3, and 4, respectively. A program session looks like this:
*** ACME checkbook-balancing program ***
Commands: 0=clear, 1=credit, 2=debit, 3=balance, 4=exit

Enter command: 1
Enter amount of credit: 1042.56
Enter command: 2
Enter amount of debit: 133.79
Enter command: 1
Enter amount of credit: 1754.32
Enter command: 2
Enter amount of debit: 1400
Enter command: 2
Enter amount of debit: 68
Enter command: 2
Enter amount of debit: 50
Enter command: 3
Current balance: $1145.09
Enter command: 4

When the user enters command 4 (that is, exit), the program needs to exit from the switch statement and the surrounding loop. The break statement is impossible, and we don't want to use the goto statement. Therefore, it was decided to use the return statement, which would cause the program to terminate and return to the operating system.

/* Balances a checkbook */

#include <stdio.h>

int main(void)
{
    
    
  int cmd;
  float balance = 0.0f, credit, debit;

  printf("*** ACME checkbook-balancing program ***\n");
  printf("Commands: 0=clear, 1=credit, 2=debit, ");
  printf("3=balance, 4=exit\n\n");

  for (;;) {
    
    
    printf("Enter command: ");
    scanf("%d", &cmd);
    switch (cmd) {
    
    
      case 0:
        balance = 0.0f;
        break;
      case 1:
        printf("Enter amount of credit: ");
        scanf("%f", &credit);
        balance += credit;
        break;
      case 2:
        printf("Enter amount of debit: ");
        scanf("%f", &debit);
        balance -= debit;
        break;
      case 3:
        printf("Current balance: $%.2f\n", balance);
        break;
      case 4:
        return 0;
      default:
        printf("Commands: 0=clear, 1=credit, 2=debit, ");
        printf("3=balance, 4=exit\n\n");
        break;
    }
  }
}

practice questions

1. What is the output of the following program fragment?

i = 1;
while (i <= 128){
    
    
	printf("%d ", i);
	i *= 2;
}

1 2 4 8 16 32 64 128
 
2. What is the output of the following program fragment?

i = 9384;
do {
    
    
	printf("%d ", i);
	i /= 10;
} while (i > 0);

9384 938 93 9

3. What is the output of the following for statement?

for (i = 5, j = i - 1; i > 0, j > 0; --i , j = i - 1)
	printf("%d ", i);

5 4 3 2

4. Which of the following statements is not equivalent to the other two statements (assuming the loop body is the same)?

  (a) for (i = 0; i < 10; i++)...
  (b) for (i = 0; i < 10; ++i)...
  (c) for (i = 0; i++ < 10; )...

c
 5. Which of the following statements is not equivalent to the other two statements (assuming the loop body is the same)?

  (a) while (i < 10) {
    
    ...}
  (b) for (; i < 10;) {
    
    ...}
  (c) do {
    
    ...} while (i < 10);

c

6. Rewrite the program fragment in Exercise 1 as a for statement.

for (i = 1; i <= 128; i *= 2) {
    
    
	pritnf("%d ", i);
}

7. Rewrite the program fragment in Exercise 2 as a for statement.

for (i = 9384; i > 0; i /= 10) {
    
    
	printf("%d ", i);
}

8. What is the output of the following for statement?

for (i = 10; i >= 1; i /= 2)
	printf("%d ", i++);

10 5 3 2 [1]
9. Rewrite the for statement in Exercise 8 as an equivalent while statement. In addition to the while loop itself, one more statement is required.

i = 10;
while (i >= 1) {
    
    
	printf("%d ", i++);
	i /= 2;
}

10. Show how to replace the continue statement with the equivalent goto statement.

Solution
Label the end of the loop and `goto` that label:

```c
for (i = 0; i <= 10; i++) {
    
    
    if (i % 2 == 1)
        continue;
    printf("%d ", i);
}

is the same as

for (i = 0; i <= 10; i++) {
    
    
    if (i % 2 == 1)
        goto end;
    printf("%d ", i);
    end:
}

11. What is the output of the following program fragment?

sum = 0;
for (i = 0; i < 10; i++) {
    
    
	if (i % 2)
		continue;
	sum += i;
}
printf("%d\n", sum);

20

  1. The following "prime test" loop appears as an example in Section 6.4:
for (d = 2; d < n; d++)
	if (n % d == 0)
	break;

This loop is not very efficient. It is not necessary to divide n by all numbers from 2 to n-1 to judge whether it is a prime number. In fact, only divisors of the square root not greater than n need be checked. Use this to modify the loop. Hint: Don't try to find the square root of n, use d*d to compare n.
solution

for (d = 2; d * d <= n; d++) {
    
    
	if (n % d == 0)
		break;
}

13. Rewrite the following loop so that its loop body is empty.

for (n = 0; m > 0; n++)
	m /= 2;

Solution

for (n = 0; m > 0; n++, m /= 2) {
    
    
	;
}

14. Find the error in the following program fragment and correct it.

if (n % 2 == 0);
	printf("n is even\n");

remove semicolon

programming questions

  1. Write a program to find the largest number in a series of numbers entered by the user. The program needs to prompt the user to enter numbers one by one. When the user enters 0 or a negative number, the program must display the largest non-negative number that has been entered:
    Enter a number: 60
    Enter a number: 38.3 Enter a number
    : 4.89
    Enter a number: 100.62
    Enter a number: 75.2295
    Enter a number: 0
    The largest number entered was 100.62
      Note that the number entered is not necessarily an integer.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
    
    
	float number, max = 0;

	printf("Enter a number: ");
	scanf("%f", &number);
	while (number > 0) {
    
    
		if (number > max) {
    
    
			max = number;
		}
		printf("Enter a number: ");
		scanf("%f", &number);
	}
	
	printf("The largest number entered was %.2f\n", max);

	return 0;
}

There is a problem:
prinf and scanf are used twice

#include <stdio.h>

int main(void) {
    
    

    float largest = 0.0f;
    float current;

    do {
    
    
        printf("Enter a number: ");
        scanf("%f", &current);

        if (current > largest)
            largest = current;
    } while (current > 0);

    printf("\nThe largest number entered was %f\n", largest);

    return 0;
}
  1. Write a program that requires the user to enter two integers, and then calculate and display the greatest common divisor (GCD) of these two integers:
    Enter two integers: 12 28
    Greatest common divisor: 4
      Tip: The classic algorithm for finding the greatest common divisor is the Euclid algorithm, The method is as follows: Let the variables m and n store the values ​​of two numbers respectively. If n is 0, stop, and the value in m is GCD; otherwise, calculate the remainder of dividing m by n, store n in m, and store the remainder in n. Then repeat the above process, each time to determine whether n is 0 or not.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
    
    
	int m, n, temp;

	printf("Enter two integers: ");
	scanf("%d%d", &m, &n);

	do {
    
    
		if (n == 0) {
    
    
			printf("Greatest common divisor: %d\n", m);
			break;
		}
		else {
    
    
			temp = n;
			n = m % n;
			m = temp;
		}

	} while (1);


	return 0;
}

Existing problems:
more judgment statements are used; an infinite loop is adopted

#include <stdio.h>

int main(void) {
    
    

    int m, n, r;

    printf("Enter two integers: ");
    scanf("%d%d", &m, &n);

    while (n != 0) {
    
    
        r = m % n;
        m = n;
        n = r;
    }

    printf("Greatest common divisor: %d\n", m);

    return 0;
}

  1. Write a program that asks the user to enter a fraction and then reduce it to its lowest terms: Enter
    a fraction: 6/12
    In lowest terms: 1/2
      Hint: To reduce a fraction to its lowest terms, first calculate the numerator and denominator, then divide both numerator and denominator by the greatest common divisor.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int euclid(int m, int n);
int main(void)
{
    
    
	int m, n, gcd;

	printf("Enter a fraction: ");
	scanf("%d/%d", &m, &n);

	gcd = euclid(m, n);

	printf("In lowest terms: %d/%d\n", m / gcd, n / gcd);

	return 0;
}

int euclid(int m, int n)
{
    
    
	int r;

	while (n != 0) {
    
    
		r = m % n;
		m = n;
		n = r;
	}

	return m;
}

There is a problem:
scanf("%d /%d", &m, &n);

#include <stdio.h>

int main(void) {
    
    

    int num, denom, n, m, r;

    printf("Enter a fraction: ");
    scanf("%d /%d", &num, &denom);

    m = num;
    n = denom;

    while (n != 0) {
    
    
        r = m % n;
        m = n;
        n = r;
    }

    printf("In lowest terms: %d/%d\n", num / m, denom / m);

    return 0;
}
  1. Add a loop to the broker.c program in Section 5.2 so that the user can enter multiple trades and the program can calculate the commission each time. The program terminates when the transaction amount entered by the user is 0.
    Enter value of trade: 30000
    Commission: $166.00
    Enter value of trade: 20000
    Commission: $144.00
    Enter value of trade: 0
/* Calculates a broker's commission */

#include <stdio.h>

int main(void) {
    
    

    float commission, value;
    
    printf("Enter value of trade: ");
    scanf("%f", &value);

    while (value > 0) {
    
    

        if (value < 2500.00f)
            commission = 30.00f + .017f * value;
        else if (value < 6250.00f)
            commission = 56.00f + .0066f * value;
        else if (value < 20000.00f)
            commission = 76.00f + .0034f * value;
        else if (value < 50000.00f)
            commission = 100.00f + .0022f * value;
        else if (value < 500000.00f) 
            commission = 155.00f + .0011f * value;
        else
            commission = 255.00f + .0009f * value;

        if (commission < 39.00f)
            commission = 39.00f;

        printf("Commission: $%.2f\n\nEnter value of trade: ", commission);
        scanf("%f", &value);
    }
    
    return 0;
}

  1. Programming Problem 1 in Chapter 4 requires writing a program to display the reverse order of two-digit numbers. Design a more general program that can handle numbers with one, two, three, or more digits. Tip: Use a do loop to repeatedly divide the entered number by 10 until the value reaches 0.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
    
    
	int number, amount = 0, temp, sum = 0, rank = 1;

	printf("Enter a number: ");
	scanf("%d", &number);

	/* 计算数字的位数 */
	temp = number;
	do {
    
    
		temp /= 10;
		amount++;
	} while (temp != 0);

	for (int i = 1; i <= amount; i++) {
    
    
		temp = number % 10;
		/* 计算对应位数的权重 */
		for (int j = 1; j <= amount - i; j++) {
    
    
			rank *= 10;
		}
		sum += temp * rank;
		number /= 10;
		rank = 1;
	}

	printf("The reversal is: %d\n", sum);

	return 0;
}

Problem:
Too stupid

#include <stdio.h>

int main(void) {
    
    

    int n;

    printf("Enter an integer: ");
    scanf("%d", &n);

    printf("Digits reversed: ");

    do {
    
    
        printf("%d", n % 10);
        n /= 10;
    } while (n != 0);

    printf("\n");

    return 0;
}
  1. Write a program that prompts the user to input a number n, and then displays all the square values ​​of even numbers from 1 to n. For example, if the user enters 100, the program should display the following:
    4
    16
    36
    64
    100
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
    
    
	int n;

	printf("Enter a number: ");
	scanf("%d", &n);

	for (int i = 2; i * i <= n; i += 2) {
    
    
		printf("%d\n", i * i);
	}

	return 0;
}

#include <stdio.h>

int main(void) {
    
    

    int n, i;

    printf("Enter a number: ");
    scanf("%d", &n);

    for (i = 1; i * i <= n; i++) {
    
    
        if ((i * i) % 2 != 0)
            continue;
        printf("%d\n", i * i);
    }

    return 0;
}
  1. Rearrange the program square3.c to initialize, judge and increment the variable i in the for loop. No need to rewrite the program, especially don't use any multiplication.
/* Prints a table of squares using an odd method */

#include <stdio.h>

int main(void) {
    
    

    int i, n, odd, square;

    printf("This program prints a table of squares.\n");
    printf("Enter number of entries in table: ");
    scanf("%d", &n);

    odd = 3;
    for (i = 1, square = 1; i <= n; odd += 2, ++i) {
    
    
        printf("%10d%10d\n", i, square);
        square += odd;
    }
    return 0;
}
  1. Write a program to display a monthly calendar. The user specifies the number of days in the month and the day of the week when the month starts:
    Enter number of days in month: 31
    Enter starting day of the week (1=Sun, 7=Sat): 3
    1 2 3 4 5
    6 7 8 9 10 11 12 13
    14 15 16 17 18 19 20
    21 22 23 24 25 26 27
    28 29 30 31
      Tip: This program is not as difficult as it looks. The most important part is a for statement that uses the variable i to count from 1 to n (where n is the number of days in the month), each value of i needs to be displayed in the for statement. In the loop, use an if statement to determine whether i is the last day of a week, and if so, display a newline.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)
{
    
    
	int days, startDay;

	printf("Enter number of days in month: ");
	scanf("%d", &days);
	printf("Enter starting day of the week (1=Sun, 7=Sat): ");
	scanf("%d", &startDay);

	for (int i = 1; i <= days; i++) {
    
    
		
	}
	
	return 0;
}

Existing problem: no idea, stupid
idea: a variable controls the loop, and a variable is responsible for displaying numbers

#include <stdio.h>

int main(void) {
    
    

    int n, day, weekday, i;

    printf("Enter number of days in month: ");
    scanf("%d", &n);
    printf("Enter starting day of the week (1=Mon, 7=Sun): ");
    scanf("%d", &weekday);

    printf("\n Mo Tu We Th Fr Sa Su\n");

    for (i = 1, day = 1; i <= n + weekday - 1; i++) {
    
    
        if (i < weekday)
            printf("   ");
        else
            printf("%3d", day++);
        if (i % 7 == 0)
            printf("\n");
    }

    printf("\n");
    return 0;
}
  1. Programming question 8 in Chapter 2 requires programming to calculate the remaining loan amount after the first, second, and third month repayments. Modify the program to require the user to enter the number of loan repayments and display the remaining loan amount after each repayment.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void) {
    
    

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


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

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

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

    printf("Enter time of payment: ");
    scanf("%d", &time);

    for (int i = 0; i < time; i++) {
    
    
        loan = loan - payment + (loan * rate / 100.0f / 12.0f);
        printf("Balance remaining after %d payment: $%.2f\n", i + 1, loan);
    }

    return 0;
}
#include <stdio.h>

int main(void) {
    
    

    float loan = 0.0f,
          rate = 0.0f,
          payment = 0.0f;
    int i,
        num_of_payments;

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

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

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

    printf("Enter number of payments: ");
    scanf("%d", &num_of_payments);

    for (i = 1; i <= num_of_payments; i++) {
    
    
        loan = loan - payment + (loan * rate / 100.0 / 12.0);
        printf("Balance remaining after payment %d: $%.2f\n", i, loan);
    }

    return 0;
}
  1. Programming Problem 9 in Chapter 5 asks you to write a program to determine which date is earlier. Generalize the program so that the user can enter any number of dates. Use 0/0/0 to indicate the end of input, no more date input.
    Enter a date (mm/dd/yy): 3/6/08
    Enter a date (mm/dd/yy): 5/17/07
    Enter a date (mm/dd/yy): 6/3/07
    Enter a date (mm/dd/yy): 0/0/0
    5/17/07 is the earliest date

Existing problem: Stupid again

#include <stdio.h>

int main(void) {
    
    

    int d1, d2, m1, m2, y1, y2;

    printf("Enter a date (mm/dd/yy): ");
    scanf("%d /%d /%d", &m1, &d1, &y1);

    while (1) {
    
    
        printf("Enter a date (mm/dd/yy): ");
        scanf("%d /%d /%d", &m2, &d2, &y2);

        if (d2 == 0 && m2 == 0 && y2 == 0)
            break;
        if (y2 < y1 || (y1 == y2 && m2 < m1) ||
            (y1 == y2 && m1 == m2 && d2 < d1)) {
    
    

            d1 = d2;
            m1 = m2;
            y1 = y2;
        } 
    }

    printf("%d/%d/%.2d is the earliest date\n", m1, d1, y1);

    return 0;
}

  1. The value of the mathematical constant e can be expressed by an infinite series:
       insert image description here
      write a program and use the following formula to calculate the approximate value:
    insert image description here

Here n is an integer entered by the user.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void) {
    
    

    int n, factorial = 1;
    float approximateValue = 1;

    printf("Enter a number: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
    
    
        for (int j = 1; j <= i; j++) {
    
    
            factorial *= j;
        }
        approximateValue += 1.0f / factorial;
        factorial = 1;
    }

    printf("e = %f", approximateValue);

    return 0;
}

There are problems: it is complicated, the key is to find the relationship between the external variable i and the internal variable

#include <stdio.h>

int main(void) {
    
    

    int i, n, denom;
    float e;

    printf("Enter integer n: ");
    scanf("%d", &n);

    for (i = 1, denom = 1, e = 1.0f; i <= n; i++) {
    
    
        e += 1.0f / (denom *= i);
    }
    printf("Approximation of e: %f\n", e);

    return 0;
}
  1. Modify Programming Problem 11 so that the program continues to add until the current item is less than u, where u is a small (floating point) number entered by the user.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void) {
    
    

    int n, factorial = 1;
    float approximateValue = 1, u;

    printf("Enter a number: ");
    scanf("%d", &n);
    printf("Enter mix float: ");
    scanf("%f", &u);

    for (int i = 1; i <= n; i++) {
    
    
        for (int j = 1; j <= i; j++) {
    
    
            factorial *= j;
        }
        approximateValue += 1.0f / factorial;
        if (1.0f / factorial < u) {
    
    
            break;
        }
        factorial = 1;
    }

    printf("e = %f", approximateValue);

    return 0;
}

There is a problem:
I have not absorbed the lesson of question 11, it is time to play

#include <stdio.h>

int main(void) {
    
    

    int i, denom;
    float e, epsilon, term;

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

    for (i = 1, denom = 1, e = 1.0f, term = 1.0f; term > epsilon; i++) {
    
    
        term = (1.0f / (denom *= i));
        e += term;
    }
    printf("Approximation of e: %f\n", e);

    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46708000/article/details/124252735