I'd like to try making a program to input test scores, suddenly.
This itself can be easily achieved with what we've been doing.
This time, additionally, if a score greater than 100 was mistakenly entered,
Let's try adding a feature that automatically corrects and remembers it as
100 points.
This program itself isn't that difficult.
The following program is an example of how to achieve the processing described above.
#include <stdio.h>
int main(void)
{
int score;
printf("点数を入力して下さい:");
scanf("%d", &score);
if (score > 100) score = 100;
printf("点数は %d 点is.\n", score);
return 0;
}
"If you run this program and enter a number less than or equal to 100, the result will be as follows:"
点数を入力してください:58 入力したデータ
点数は 58 点is.
If you run this program with an input greater than 100, the result will be as follows.
点数を入力してください:135 入力したデータ
点数は 100 点is.
Here, another one, if the entered score is greater than 100,
"Adjusting the input because it's greater than 100."」
How would I add functionality to display a message like that?
It doesn't work to simply concatenate a printf statement immediately after an existing if statement.
In an if statement, only the statement immediately following the if condition is used for the judgment result.
The printf statement immediately following an if statement will be executed as a regular statement every time.
One approach is to use two if statements.As follows:
if (score > 100) printf("入力が 100 より大きいので修正します。\n");
if (score > 100) score = 100;
You can display a message by using two if statements.
"Similar to the previous section, this allows us to execute multiple statements for a single condition,"
Repeating comparisons under the same conditions is simply wasteful.
"It would be much smarter if there were a way to execute multiple statements with a single if statement."
C has a feature that allows you to group multiple statements together.
That is what's called a
block statement (complex sentence) feature.
【Block statement】
A way to group multiple sentences using {}.
This block allows you to place multiple sentences in a space that typically only allows for one.
In addition, it is customary to indent the sentences within a block quotation.
"I started by explaining
indentation, but for those who forgot, please remember it."
Using block statements, you can execute multiple processes based on the result of an if statement.
The following program adds a message display function using block statements.
#include <stdio.h>
int main(void)
{
int score;
printf("点数を入力して下さい:");
scanf("%d", &score);
if (score > 100)
{
printf("入力が 100 より大きいので修正します。\n");
score = 100;
}
printf("点数は %d 点is.\n", score);
return 0;
}
"If you run this program and enter a number less than or equal to 100, the result will be as follows:"
点数を入力してください:58 入力したデータ
点数は 58 点is.
If you run this program with an input greater than 100, the result will be as follows.
点数を入力してください:135 入力したデータ
入力が 100 より大きいので修正します。
点数は 100 点is.