PAT1005 Spell It Right
Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.
Input Specification:
Each input file contains one test case. Each case occupies one line which contains an N (≤).
Output Specification:
For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.
Sample Input:
12345
Sample Output:
one five
打串数字(其实是字符串)加起来的和的每个数字用英语输出
呜呜呜!!!我自己的代码写了90行(包括头文件)
小柳柳只写了15行。。(落泪
附上我的狗屎代码->笨拙之极用了俩switch-case学学人家柳姐姐!!
#include<iostream>
#include<iomanip>
#include<stdlib.h>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<vector>
#include<string>
using namespace std;
int main() {
int i = 0;
int m = 0;
string s;
cin >> s;
while (s[i] != '\0') {//明明string可以直接一个for循环s.length()这样加起来
m += s[i] - '0';
i ++;
}
char t[10000];
sprintf(t, "%d", m);//写spintf的时候我又忘了参数是啥!!挨打!
//上面这种使用sprintf的为方法1
方法2:string a = to_string(m);
switch (t[0] - '0') {//笨拙之极之switch1
case 0:
cout << "zero";
break;
case 1:
cout << "one";
break;
case 2:
cout << "two";
break;
case 3:
cout << "three";
break;
case 4:
cout << "four";
break;
case 5:
cout << "five";
break;
case 6:
cout << "six";
break;
case 7:
cout << "seven";
break;
case 8:
cout << "eight";
break;
case 9:
cout << "nine";
break;
}
i = 1;
while (t[i] != '\0') {
switch (t[i]-'0') {//笨拙之极之switch2
case 0:
cout << " "<< "zero" ;
break;
case 1:
cout << " "<< "one";
break;
case 2:
cout << " "<< "two";
break;
case 3:
cout << " "<< "three";
break;
case 4:
cout << " "<< "four";
break;
case 5:
cout << " "<< "five" ;
break;
case 6:
cout << " "<< "six" ;
break;
case 7:
cout << " "<< "seven" ;
break;
case 8:
cout << " "<< "eight" ;
break;
case 9:
cout << " "<< "nine" ;
break;
}
i++;
}
return 0;
}
附上小柳柳代码链接
https://www.liuchuo.net/archives/1885
#include <iostream> using namespace std; int main() { string a; cin >> a; int sum = 0; for (int i = 0; i < a.length(); i++) sum += (a[i] - '0'); string s = to_string(sum); string arr[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; cout << arr[s[0] - '0']; for (int i = 1; i < s.length(); i++) cout << " " << arr[s[i] - '0']; return 0; }
不去使用switch-case,而是把0-9对应的英文放在string数组中
最后输出也是一个遍历完事