溫馨提示×

c語言怎么把字符轉(zhuǎn)換成數(shù)字

小億
244
2023-12-28 06:46:19
欄目: 編程語言

在C語言中,可以使用以下幾種方法將字符轉(zhuǎn)換為數(shù)字:

  1. 使用atoi()函數(shù):該函數(shù)將字符串轉(zhuǎn)換為整數(shù)。需要包含<stdlib.h>頭文件。
#include <stdio.h>
#include <stdlib.h>

int main() {
    char c = '5';
    int num = atoi(&c);
    printf("%d\n", num);  // 輸出:5
    
    return 0;
}
  1. 使用sscanf()函數(shù):該函數(shù)將字符串按指定格式轉(zhuǎn)換為特定類型的值。需要包含<stdio.h>頭文件。
#include <stdio.h>

int main() {
    char c = '7';
    int num;
    sscanf(&c, "%d", &num);
    printf("%d\n", num);  // 輸出:7
    
    return 0;
}
  1. 使用字符的ASCII碼值進(jìn)行轉(zhuǎn)換:字符的ASCII碼值減去字符’0’的ASCII碼值,即可得到對應(yīng)的數(shù)字。
#include <stdio.h>

int main() {
    char c = '9';
    int num = c - '0';
    printf("%d\n", num);  // 輸出:9
    
    return 0;
}

以上是常用的字符轉(zhuǎn)換為數(shù)字的方法,具體使用哪種方法取決于實際需求和個人習(xí)慣。

0