CCF 201512-1 数位之和

有两种方法:

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

posted @ 2022-03-23 19:48  夏莱发电厂的Sensei  阅读(32)  评论(0)    收藏  举报