c algorithm exercise 1 - convert decimal to hexadecimal number

Algorithm questions:

​ Hexadecimal numbers are an integer representation that is often used in programming. It has a total of 16 symbols 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F, representing decimal numbers 0 to 15 respectively. The counting method of hexadecimal is to add 16 to 1, so the decimal number 16 is 10 in hexadecimal, and the decimal number 17 is 11 in hexadecimal, and so on, the decimal number 30 is in hexadecimal The system is 1E.
Given a non-negative integer, represent it in hexadecimal form.
Input format
The input contains a non-negative integer a, which represents the number to be converted. 0<=a<=2147483647
Output format
Outputs the hexadecimal representation of this integer

code:

#include <stdio.h>
int n;
char result[10];

int main(){
    
    
        scanf("%d",&n);  //接收标准输入
        int i =0;
        int temp=0;
        while(n!=0){
    
     
                temp = n%16;
                if(temp<=9){
    
    
                         result[i]=temp+'0'; //0~9的数字加上'0',可以将数字转化为字符
                }
                else{
    
    
                        result[i] = ((temp-10)+'A');  //字符加上数字等同于ascall的计算
                }
                i++;
                n = n/16;
             }
        // 循环输出数组内容,sizeof()计算数组长度。
        for(int p=sizeof(result)-1;p>=0;p--)
                printf("%c",result[p]);
}

Online hexadecimal conversion website
C language online compiler

Guess you like

Origin blog.csdn.net/quxuexi/article/details/124986440