Input the scores of three students, and calculate their total score and average score.
Therefore, this project will be introduced in two tasks.
A class took an exam and the results need to be outputted as required.
From the program segment below, it can be analyzed that:
#include "stdio.h"
main()
{
int x,y,z; // Define three variables x, y, z
printf("Please input the scores of three students");
scanf("%d%d%d",&x,&y,&z); /* Input the scores of three students */
printf("Output the scores of three students");
printf("x=%d,y=%d,z=%d\n",x,y,z); // Output the values of the three variables x, y, z
} // End of function body
C:\Documents and Setti...
Please input the scores of three students 87 88 91
Output the scores of three students x=87,y=88,z=91
#include "stdio.h" // File Preprocessing main() // Main Function { int x,y; // Data Declaration Part x=1; // Statement Part y=x+2; // Statement Part printf("x=%d\ny=%d\n",x,y); // Statement Part }
Click on [File] → [New], and in the dialog box that appears, click on [File] → [C++Source File] with the mouse, then change the directory where the file is saved (if necessary), enter the file name, and click [OK].
Enter the program. After the program input is complete, click the **Build** button or press F7 to compile and link. If there are no errors, click the **Execute/Run** button or press Ctrl+F5.
(File -> New, selecting C++ Source File, and console output.)
Data types in C language can be divided into:
Data type VariableName [= InitialValue], VariableName2 = InitialValue2 ......];
Example:
int x=1,y=2,z=3;
float a=1.1,b=1.2,c=-0.1;
char ch1='A',ch2='*';
printf() function:printf("format string"[, output list]);
(1) printf("I am a student\n"); // No output item (only outputting the string and a newline)
(2) printf("%d",1+2); // Output the value of 1+2
(3) printf("a=%d b=%d\n",1,1+3); // Output the value of 1 and the value of 1+3
(4) printf("%d %f\n",1.212,5); Try it yourself!
/* %d expects an integer, but receives a float (1.212). %f expects a float, but receives an int (5). */
#include "stdio.h"
main()
{
int x=1,y=2,z=3; /* Define three integer variables x, y, z, and initialize them to 1, 2, 3 */
float a=1.1,b=2.3;
char c1='A',c2='B'; /* Define two character variables c1, c2, and initialize them to 'A' and 'B' */
printf("Output x,y,z values\n"); // Output "Output x,y,z values" followed by a newline
printf("x=%d,y=%d,z=%d\n",x,y,z); // Output "x=1,y=2,z=3" followed by a newline
printf("Output a,b values\n");
printf("a=%f,b=%f\n",a,b);
printf("Output c1,c2 values\n");
printf("c1=%c,c2=%c\n",c1,c2);
}
Output x,y,z values
x=1,y=2,z=3
Output a.b values
a=1.100000,b=2.300000
Output c1.c2 values
c1=A,c2=B
scanf() is to receive formatted input from the keyboard.Example formats: (Guess and try!!!)
scanf("%d,%d",&a,&b); vs scanf("%d %d",&a,&b); vs scanf("%d%d",&a,&b);
Whitespace characters (also known as ordinary characters) in the format string (e.g., space, newline, tab) will match any combination of whitespace characters in the input.
Non-whitespace characters in the format string (e.g., `,` or `:`) must be inputted exactly as they are in the format string when entering data.
Consists of the starting addresses of several input items, separated by commas between adjacent item addresses.
The method to represent the starting address of a variable is: &VariableName
The "&" is the address operator. For example, in Example 1-1, "&x" in scanf("%d%d%d",&x,&y,&z) refers to the starting address of variable x in memory. Its function is to input three integers from the keyboard and store them starting at the memory units of &x, &y, &z, respectively, i.e., assign the three integers to x, y, and z.
Analysis: This problem requires inputting and outputting both integer scores (%d) and character codes (%c). When using scanf to read characters after a number, any non-whitespace separator in the format string (e.g., :) must be matched in the input.
#include "stdio.h"
main()
{
char c1,c2;
int x,y;
printf("Please input A's score and codename (e.g., 87:A): ");
scanf("%d:%c",&x,&c1);
printf("Please input B's score and codename (e.g., 76:B): ");
scanf("%d:%c",&y,&c2);
printf("Output A's code and score: \n");
printf("%c:%d\n",c1,x);
printf("Output B's code and score: \n");
printf("%c:%d\n",c2,y);
}
Please input A's score and code: 87:A
Please input B's score and code: 76:B
Output A's code and score:
A:87
Output B's code and score:
B:76
The escape character "\n" has been mentioned, which is a newline.
Another common escape character is "\t", which horizontally tabs to the next output field.
#include "stdio.h"
main()
{
printf("%d\t%d\t%d\n",1,2,3);
}
1 2 3
Previously, we learned the general format of the output statement: printf("format string"[, output list]);
Commonly used format string representations are as follows:
#includemain() { int a=123; long b=123456; /* Output value of int type data 'a' using four different formats */ printf("a=%d,a=%5d,a=%-5d,a=%2d\n",a,a,a,a); /* Output value of long type data 'b' using four different formats */ printf("b=%ld,b=%8ld,b=%-8ld,b=%2ld\n",b,b,b,b); printf("a=%ld\n",a); // Output int type data 'a' using %ld printf("b=%d\n",b); // Output long type data 'b' using %d }
a=123,a= 123,a=123 ,a=123
b=123456,b= 123456,b=123456 ,b=123456
a=123
b=123456
123.123 .123.123456. 123456.123456 .123456.
#include "stdio.h"
main()
{
float f=123.456;
double d1,d2;
d1=111111.11111111;
d2=222222.22222222;
printf("f=%f,f=%12f,f=%12.2f,f=%-12.2f,f=%.0f,f=%.2f\n",f,f,f,f,f,f);
printf("d1+d2=%f\n",d1+d2);
}
123.46.123.46 .putchar() function.
#include "stdio.h"
main()
{
char ch1,ch2,ch3;
ch1='S';
ch2='u';
ch3='n';
putchar(ch1); putchar(ch2); // Output ch1, ch2 values
putchar(ch3); putchar('\n'); // Output ch3 value and newline
putchar(ch1); putchar('\n'); // Output ch1 value and newline
putchar('u'); putchar('\n'); // Output character 'u' and newline
putchar(ch3); putchar('\n'); // Output ch3 value and newline
}
Sun
S
u
n
Note: The putchar() function can only be used for outputting a single character, and can only output one character at a time. From a functional perspective, the printf() function can completely replace putchar(); using putchar() also requires the preprocessor command #include "stdio.h" at the beginning of the program.
getchar() function.
#include "stdio.h"
main()
{
char ch;
printf("Please input a character: ");
ch=getchar(); // Input a character from the keyboard and assign it to variable ch
putchar(ch);putchar('\n'); // Output the value of ch and a newline
putchar(getchar()); // Input a character from the keyboard and output it
putchar('\n');
}
Format of getchar(): getchar();
Function of getchar(): Inputs a single character from the keyboard. From a functional perspective, the scanf() function can completely replace getchar().
Note: The getchar() function can only be used for single character input, and can only input one character at a time. Similarly, using getchar() also requires the preprocessor command #include "stdio.h" at the beginning of the program.
A string constant is a sequence of characters enclosed in double quotes. For example, "How do you do." is a string constant. In the C language, the system automatically appends a null character '\0' at the end of every string constant as a marker for the end of the string.
Please note the difference between a character constant and a string constant. For instance, 'a' is a character constant, occupying one byte in memory; while "a" is a string constant, occupying two bytes of storage space, one of which is used to store '\0'. Two consecutive double quotes "" is also a string constant, called the "null string," but it still occupies one byte of storage space for '\0'.
Note:
printf("%s") and strlen() stop at the first \0). Note that the compiler automatically appends a terminating '\0' byte to each string literal."abc\067de" → stored bytes: 'a','b','c','7','d','e','\0' ; strlen returns 6, sizeof returns 7."abc\0de" → stored bytes: 'a','b','c',0,'d','e','\0' ; strlen returns 3 (stops at the embedded \0), sizeof returns 7 (includes all bytes plus the literal terminator).(A) 'A' (B) "house" (C) How do you do (D) $asd
Analysis: A string constant is a sequence of characters enclosed in a pair of double quotes. The answer is ??
scanf("%f%f%f", &a, &b, &c); to assign 10.0 to a, 22.0 to b, and 33.0 to c, which of the following four answers (A, B, C, D) is incorrect?Please write a complete C program to make the execution result as follows:
A. 10<Enter> 22<Enter> 33
B. 10.0,22.0,33.0<Enter>
C. 10.0<Enter> 22.0 33.0<Enter>
D. 10 22<Enter> 33<Enter>
#include "stdio.h"
main()
{
float a,b,c;
scanf("%f%f%f", &a, &b, &c);
printf("a=%.1f,b=%.1f,c=%.1f\n", a, b, c);
}
Analysis:
scanf("%f%f%f", &a, &b, &c) requires the numbers to be separated by either a space or a newline when entering the data. Therefore, answers A, C, and D are all correct, and only B is incorrect. If the input data format were 10.0,22.0,33.0<Enter>, the input statement should be written as: scanf("%f,%f,%f", &a, &b, &c);.Answer: B.
scanf(“%d”,k) cannot correctly obtain a value for the float type variable k?Analysis: Since k is a real type variable, the format string should be “%f”, and the address operator & is missing before the variable.
Correct Answer Format: scanf("%f",&k);
#include "stdio.h"
main()
{
int a,b;
scanf("%d%d", &a,&b);
printf("a+b=%d\n",a+b);
}
A. a+b=46 B. Syntax Error C. a+b=12 D. Undefined Value
Analysis: The input statement scanf("%d%d", &a,&b) requires the two input numbers to be separated by a space or a newline. However, the problem specifies the two numbers are separated by a comma. This causes the value of b to be an undefined value. Therefore, the result is undefined.
Answer: D.
printf() statements after the given program segment.
// Reference Program:
#include "stdio.h"
main()
{
int x1, x2;
char y1, y2;
scanf("%d%d", &x1,&x2);
scanf("%c%c", &y1,&y2);
printf("x1=%d,x2=%d\n", x1,x2);
printf("y1=%c,y2=%c\n", y1,y2);
}
10 20AB — that is, a space between the two integers, then immediately the characters A and B with no intervening whitespace.
Behavior of the original code:
scanf("%d%d", &x1,&x2) reads two integers and leave out whitespace character.scanf("%c%c", &y1,&y2) reads the next two characters exactly — it does not skip whitespace. Therefore any space or newline remaining in the buffer becomes y1.A class took an exam. Now, the scores of several students need to be inputted into the computer, their average and total scores calculated, and then outputted as required.
First, arithmetic operations and arithmetic expressions;
Second, assignment operations and assignment expressions;
Additionally, it is necessary to master C language's unique operations and operators that are not demonstrated in this task but are often used in C programs.
#include "stdio.h"
main()
{
int x,y,z;
float sum,avg; // Define float variables sum and avg
printf("Please input the scores of three students: ");
scanf("%d%d%d",&x,&y,&z); /* Input */
sum=x+y+z; // Assign the value of x+y+z to a variable sum
avg=sum/3; // Assign the value of sum/3 to variable avg
printf("Please output the total score and average score of the three students: ");
printf("sum=%.2f,avg=%.2f\n",sum,avg); // Output sum and avg values (2 decimal places)
}
Please input the scores of three students 78 81 93
Please output the total score and average score of the three students sum=252.00,avg=84.00
+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulo/Remainder)
Here, it is necessary to specifically mention:
(1) Regarding the Division Operation /
5/2=2.-5/3=-1.(2) Regarding the Modulo/Remainder Operation %
5%3=2, 3%5=3, 5%(-3)=2, -5%3=-2.5.2%3 is a syntax error.(1) Concept of an Expression
A sequence of operands (constants, variables, and functions) connected by operators and parentheses, conforming to the C language syntax rules, is called an expression.
A single constant or variable can be regarded as a special case of an expression. Expressions consisting of single constants or variables are called simple expressions; others are called complex expressions.
(2) Concept of an Arithmetic Expression
The operators in the expression are all arithmetic operators. Examples: 3+2*5, (x+y)/2+3, 5%2+3 are all arithmetic expressions.
(1) The precedence of arithmetic operators is: first *, /, %, then +, -.
(2) Operations within parentheses are performed first.
High double ← float
↑
long
↑
unsigned
↑
Low int ← char,short
Example:
(double)x is equivalent to (double)(x) // Convert the value of variable x to double type(int)(x+y) // Convert the result of x+y to int type(float)7/2 is equivalent to (float)(7)/2 // Convert 7 to float type, then divide by 2 (=3.5)(float)(7/2) // Convert the result of integer division 7/2 (which is 3) to float type (3.0)The assignment symbol "=" is the assignment operator, and its function is to assign the value of an expression to a variable.
The general form of the assignment operator is: Variable = Assignment_Expression
Examples of incorrect usage:
x+=3 is equivalent to x=x+3
x+=5+8 is equivalent to x=x+(5+8)
x*=y+2 is equivalent to x=x*(y+2)
x/=x+y is equivalent to x=x/(x+y)
x/=8 is equivalent to x=x/8
x%=7 is equivalent to x=x%7
x%=(4-2) is equivalent to x=x%(4-2)
#include "stdio.h"
main()
{
int x,y,z;
float a,b,c; // Define three single-precision float variables a,b,c
x=1; // Assign 1 to variable x, so x's value is 1
y=2;
z=3;
a=1.1; // Assign 1.1 to variable a, so a's value is 1.1
b=2.1;
c=3.5;
x=x+y+z; // Assign x+y+z value to variable x. x = (1+2+3), so x=6
printf("x=%d\n",x);
y*=y+1; // Assign y*(y+1) to y. y = 2*(2+1), so y=6
printf("y=%d\n",y);
z=(int)a%(int)b; // z=1%2, so z=1
printf("z=%d\n",z);
a+=a+b+c; // a=a+(a+b+c). a = 1.1+(1.1+2.1+3.5), so a=9.9
printf("a=%f\n",a);
}
x=6
y=6
z=1
a=9.900000
Function: The increment operation increases the value of a single variable by 1; the decrement operation decreases it by 1.
Usage and Rules:
Increment and decrement operators have two forms of usage:
1) Prefix Operation: The operator is placed before the variable: ++x or --x.
First, the variable's value is incremented (or decremented) by 1, and then the changed value participates in the subsequent expression calculation.
#include "stdio.h"
main()
{
int x=2,y,z;
printf("x=%d\n",x); // Output: x=2
y=++x; // x is incremented first (x=3), then assigned to y (y=3)
printf("x=%d y=%d\n",x,y); // Output: x=3 y=3
++x; // x is incremented (x=4)
printf("x=%d\n",x); // Output: x=4
y=++x+2; // x is incremented first (x=5), then x+2 (5+2=7), then assigned to y (y=7)
printf("x=%d y=%d\n",x,y); // Output: x=5 y=7
z=--x; // x is decremented first (x=4), then assigned to z (z=4)
printf("x=%d z=%d\n",x,z); // Output: x=4 z=4
--x; // x is decremented (x=3)
printf("x=%d\n",x); // Output: x=3
}
Note: The increment and decrement operators cannot be used with constants or expressions.
Example: 5++, --8, ++(a+b) are all incorrect.
2) Postfix Operation: The operator is placed after the variable: x++ or x--.
First, the variable's *original value* participates in the expression calculation, and then the variable's value is incremented (or decremented) by 1.
#include "stdio.h"
main()
{
int x=2,y,z;
printf("x=%d\n",x); // Output: x=2
y=x++; // x's original value (2) is assigned to y, then x is incremented (x=3)
printf("x=%d y=%d\n",x,y); // Output: x=3 y=2
x++; // x is incremented (x=4)
printf("x=%d\n",x); // Output: x=4
y=(x++)+2; // x's original value (4) + 2 = 6 is assigned to y, then x is incremented (x=5)
printf("x=%d y=%d\n",x,y); // Output: x=5 y=6
z=x--; // x's original value (5) is assigned to z, then x is decremented (x=4)
printf("x=%d z=%d\n",x,z); // Output: x=4 z=5
x--; // x is decremented (x=3)
printf("x=%d\n",x); // Output: x=3
}
Analysis: Based on the radius, we need to calculate the area and circumference. Therefore, three variables need to be defined: radius (r), area (s), and circumference (c). Considering that the input radius might be a decimal, all three variables should be defined as float (single-precision floating-point type).
// C Code
#include "stdio.h"
main()
{
float r,s,c;
printf("Please input the radius of the circle r: ");
scanf("%f",&r);
s=3.14*r*r;
c=2*3.14*r;
printf("The area of the circle s is: %f\n",s);
printf("The circumference of the circle c is: %f\n",c);
}
Please input the radius of the circle r: 1
The area of the circle s is: 3.140000
The circumference of the circle c is: 6.280000
#define PI 3.14
This defines a symbolic constant PI with a value of 3.14. The naming rules for symbolic constants are the same as for variable names, but conventionally, symbolic constants are represented by uppercase letters.
#include "stdio.h"
#define PI 3.14 // Define a symbolic constant PI with a value of 3.14
main()
{
float r,s,c;
printf("Please input the radius of the circle r: ");
scanf("%f",&r);
s=PI*r*r;
c=2*PI*r;
printf("The area of the circle s is: %f\n",s);
printf("The circumference of the circle c is: %f\n",c);
}
Analysis: Clearly, three variables a, b, c need to be defined for the side lengths, and two variables for the perimeter (cc) and area (s). The calculation of the area requires Heron's formula: s = sqrt(l*(l-a)*(l-b)*(l-c)), where l is the semi-perimeter. We also need to define a variable l for the semi-perimeter. The square root is calculated using the sqrt() function, which requires including the math.h header at the beginning of the program.
#include "stdio.h"
#include "math.h" // For the square root function sqrt()
main()
{
int a,b,c;
float cc,l,s; // cc for perimeter, l for semi-perimeter, s for area
printf("Please input the lengths of the three sides a, b, c: ");
scanf("%d%d%d",&a,&b,&c);
cc = a + b + c;
l = cc / 2.0f; // use 2.0f to ensure float division
s = sqrt(l * (l - a) * (l - b) * (l - c));
printf("The perimeter of the triangle cc is: %f\n", cc);
printf("The area of the triangle S is: %f\n", s);
}
Please input the lengths of the three sides a,b,c: 3 4 5
The perimeter of the triangle cc is: 12.000000
The area of the triangle S is: 6.000000
Analysis: First, consider the variables to be defined: a, b, c, x1, x2, and the discriminant disc = b2 - 4*a*c. Then calculate the roots using the quadratic formula: x = (-b ± sqrt(disc)) / (2*a). Finally, output the results.
#include "stdio.h"
#include "math.h"
main()
{
float a,b,c,disc,x1,x2;
printf("Please input the coefficients a, b, c of the equation: ");
scanf("%f%f%f",&a,&b,&c); // Input a, b, c
disc=b*b-4*a*c; // Calculate the discriminant and assign it to disc
x1=(-b+sqrt(disc))/(2*a); // Calculate the roots
x2=(-b-sqrt(disc))/(2*a);
printf("The roots of the equation are x1=%f, x2=%f\n",x1,x2); // Output x1, x2 values
}
Please input the coefficients a,b,c of the equation: 1 2 1
The roots of the equation are x1=-1.000000, x2=-1.000000
Alternative Method: Instead of using the quadratic formula, we can use computational methods to approximate the roots of ax2 + bx + c = 0 by iteratively narrowing down the possible solution space. This method is especially useful when exact formulas are difficult to apply or when we want to demonstrate algorithmic thinking.
We'll use a simple incremental search method:
#include "stdio.h"
#include "math.h"
main()
{
float a, b, c;
float x, fx, tolerance = 0.01; // Tolerance for approximation
float start = -100.0, end = 100.0, step = 0.001; // Search parameters
int found = 0;
printf("Please input the coefficients a, b, c of the equation: ");
scanf("%f%f%f", &a, &b, &c);
printf("Searching for roots in range [%.1f, %.1f] with step %.3f\n", start, end, step);
// Iterative search for roots
for(x = start; x <= end; x += step) {
fx = a*x*x + b*x + c; // Calculate f(x) = ax^2 + bx + c
if(fabs(fx) < tolerance) { // Check if f(x) is close to 0
printf("Approximate root found at x = %.3f, f(%.3f) = %.6f\n", x, x, fx);
found = 1;
}
}
if(!found) {
printf("No roots found within the specified range and tolerance.\n");
printf("Try adjusting the range or tolerance parameters.\n");
}
}
Please input the coefficients a, b, c of the equation: 1 2 1
Searching for roots in range [-100.0, 100.0] with step 0.001
Approximate root found at x = -1.000, f(-1.000) = 0.000000
Note: This iterative method is computationally more intensive than the quadratic formula but demonstrates an important computational thinking approach. In practice, more sophisticated methods like Newton-Raphson are used for faster convergence.
Analysis: Since a lowercase letter is to be inputted and converted to an uppercase letter, two character variables need to be defined. The conversion formula between lowercase and uppercase letters is: lowercase_letter = uppercase_letter + 32 (based on ASCII values). Thus, uppercase_letter = lowercase_letter - 32. Finally, output the results.
#include "stdio.h"
main()
{
char c1,c2; // Define two character variables c1, c2
printf("Please input a lowercase letter: ");
scanf("%c",&c1); // Input the lowercase letter
c2=c1-32; // Calculate the corresponding uppercase letter
// Output the original letter and its corresponding uppercase letter and ASCII value
printf("Original letter is %c, Uppercase letter is %c\n",c1,c2);
// To output the ASCII code, cast the char to an int with %d format specifier
printf("ASCII code of %c is %d, ASCII code of %c is %d\n", c1, c1, c2, c2);
}
Please input a lowercase letter: a
Original letter is a, Uppercase letter is A
ASCII code of a is 97, ASCII code of A is 65