解题思路:
现代作品
注意事项:
不支持C++11,不能愉快地to_string了...
参考代码:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <string> #include <vector> #include <memory.h> #include <stdio.h> using namespace std; string getAn(int n) { string an; char temp[7] = { 0 }; for (int i = 1; i <= n; i++) { if (i == n) sprintf(temp, "sin(%d)", i); else { if (i%2) sprintf(temp, "sin(%d-", i); else sprintf(temp, "sin(%d+", i); } an += temp; memset(temp, 0x00, sizeof(temp)); } for (int i = 1; i < n; i++) { an += ")"; } return an; } string getSn(int n) { string sn; char num1[2] = { 0 }, num2[2] = { 0 }; for (int i = 1; i <= n; i++) { sprintf(num1, "%d", n - i + 2); sprintf(num2, "%d", n - i + 1); if (i == 1) sn = "sin(1)" + string("+") + string(num2); else sn = "(" + sn + ")" + getAn(i) + "+" + num2; } return sn; } int main(int argc, char** argv) { int n = 0; cin >> n; cout << getSn(n) << endl; system("pause"); return 0; } 【思路二】 #include <cstdio> #include <iostream> #include <string> #include <algorithm> using namespace std; string A(int i, int n) { string ans = "sin("; char I = '0' + i; if(i == n) return ans + I + ')'; else if(i % 2 == 1) { return ans + I + '-' + A(i + 1, n) + ')'; } else { return ans + I + '+' + A(i + 1, n) + ')'; } } string S(int n, int sum) { char Sum = '0' + sum - n; if(n == 1) { return A(1,1) + '+' + Sum; } else { return '(' + S(n-1, sum) + ')' + A(1,n) + '+' + Sum; } } int main(void) { int n; cin >> n; cout << S(n,n+1) << endl; return 0; }
0.0分
0 人评分