CCF 201512-1 數位之和
阿新 • • 發佈:2022-03-23
有兩種方法:
1.普通的方法:
#include<iostream> using namespace std; int main(){ string str; cin >> str; int ans = 0; for(int i = 0 ; i < str.size(); i++){ ans = ans + (str[i] - '0'); } cout << ans << endl; }
2.通過內建函式:
用C++的庫函式atoi() * atoi函式把字串轉換成整型數。是ASCII to integer 的縮寫。
在C++中直接包含在標頭檔案stdlib.h標頭檔案中,使用時要包含標頭檔案#include<stdlib.h>。
atoi()函式的的形式引數為指標,所以要將字串指標來傳遞。
當atoi()讀取到非數字字元時將會停止轉換。(參考https://blog.csdn.net/weixin_4420832)
#include<bits/stdc++.h> using namespace std; int main(){ char str[12]; cin >> str; int n; n = atoi(str); int ans = 0; for(int i = 0 ; i < strlen(str); i++){ ans += n % 10; n = n / 10; } cout << ans << endl; }
咱就是為了多記一個函式而已QWQ