C language judges whether a character is a number and implements an accumulator

problem introduction

1. Input a character, judge whether it is a number, output Yes, not output No.
2. Construct an accumulator, input 10 numbers and sum it.

Judgment character

The character variable in the C language is char, which is stored in the value of the ASCII code. As long as we know the ASCII code value of the numbers 0 to 9 , we can judge whether the input character is a number.
Alt

  1. What needs to be remembered is that the ASCII code decimal number of the number 0 (the following are all decimals) is 48
  2. The ASCII code for capital letter A is 65
  3. lowercase a is 97
  4. The difference between uppercase and lowercase letters is 32, and the uppercase and lowercase conversions can be performed based on this difference.

code example

include<stdio.h>

int main(){
    
    
    char a;
    scanf("%c",&a);
    if((a>='0') && (a<='9'))
        printf("Yes");
    else
        printf("No");
    return 0;
}

accumulator

To achieve the sum of 10 numbers , we need to use a loop statement

for(表达式1;表达式2;表达式3;){
    
    
	循环体;
	}
  1. Expression 1 is the initial expression, which will be executed once at the beginning of the loop to set the initial condition of the loop
  2. Expression 2 is a conditional expression, and the loop will exit when the condition is not met
  3. Expression 3 is the expression at the end of the loop body, that is, after the execution of the loop body, Expression 3 will be executed. In many cases, it is an expression with self-increment or self-decrement operation, so that the loop condition gradually becomes "invalid".

code example

#include<stdio.h>

 void main()
 {
    
    
     int i,s=0,temp;
     for(i=0;i<10;i++){
    
    
         scanf("%d",&temp);
         s += temp;
     }
    printf("%d",s);
 }

In this example, we use the intermediate variable temp to receive the value entered each time, and the value of temp is added to the variable s and it will be overwritten in a new loop

 #include<stdio.h>

 void main(){
    
    
     int n=10,temp,s=0;
     while (n)
     {
    
    
        scanf("%d", &temp);
        s += temp;
        n--;
     }
     printf("%d",s);
 }

Can be further simplified:

 #include<stdio.h>

 void main(){
    
    
    int n=10,temp,s=0;
    while (n--)
    {
    
    
        scanf("%d",&temp);
        s += temp;
    }
     printf("%d",s);
 }

The value of the expression is to n--take the value of n first and then decrement; --nthe value of the expression is decremented first and then takes the value of n

[1]:

"""
Created on Sat Mar 12 18:40:03 2022

@author: YLH
"""

Guess you like

Origin blog.csdn.net/m0_46282316/article/details/123338574
Recommended