就是打印下面这两个复杂的式子:
input | output |
---|---|
3 |
((sin(1)+3)sin(1–sin(2))+2)sin(1–sin(2+sin(3)))+1 |
一看就知道需要使用递归打印了,关键是如何安排好递归才能精确地打印,
下面两个函数分别处理两个式子,综合起来得到答案。
其中注意增加mItoS这个函数是必要的,因为当n >= 10的时候,那么就不能直接转换成为char了。
#include <string> #include <vector> #include <cmath> #include <algorithm> #include <iostream> #include <map> using namespace std; string mItoS(int n) { string s; while (n) { s.push_back(n % 10 + ‘0‘); n /= 10; } reverse(s.begin(), s.end()); return s; } string printAn(int n) { if (n < 1) return ""; if (1 == n) return "sin(1)"; string s = printAn(n-1); string s2; if ((n-1) % 2) { s2 = "-sin("; } else s2 = "+sin("; s2 += mItoS(n); s2.push_back(‘)‘); s.insert(s.end() - (n-1), s2.begin(), s2.end()); return s; } string printSn(int n, int c = 1) { if (1 == n) { string s; s.append(c-1, ‘(‘); s += printAn(1); s.push_back(‘+‘); s += mItoS(c); return s; } string s = printSn(n-1, c+1); s.push_back(‘)‘); s += printAn(n); s.push_back(‘+‘); s += mItoS(c); return s; } void SinusDances1149() { int n = 0; cin>>n; cout<<printSn(n); }
有人不使用递归也做到了,不过那样更难想到了,因为要观察其中的规律,更加复杂,不过他的代码更加简洁,下面是她论坛上找到的程序:
#include<stdio.h> int mainSinus() { int n,i,j; scanf("%i",&n); for(i=1;i<n;i++) printf("("); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) { if(j>1) printf((j&1)?"+":"-"); printf("sin(%i",j); } for(j=1;j<=i;j++)printf(")"); printf("+%i",n+1-i); if(i!=n)printf(")"); } return 0; }
Timus 1149. Sinus Dances 打印复杂公式,布布扣,bubuko.com
Timus 1149. Sinus Dances 打印复杂公式
原文:http://blog.csdn.net/kenden23/article/details/24476215