C++一元多项式求导

C++一元多项式求导

 

这个题难度不大但是坑有点多,要考虑的点有几个:

1.测试用例为x 0 这个直接输出 0 0即可。

2.注意空格的输出

3.测试点3我好几次都没过,最后参考了别的答案加以修改才通过。

C++一元多项式求导

测试点3没过的代码:

 1 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 
 6 struct Derivative
 7 {
 8     int ratios;//系数
 9     int time;//次数
10 };
11 
12 int main()
13 {
14     int ratios;
15     int time;
16 
17     //接收输入
18     vector<Derivative> derivatives;
19     while(cin >> ratios >> time)
20     {
21         Derivative d;
22         d.ratios = ratios;
23         d.time = time;
24         derivatives.push_back(d);
25         char c = cin.get();
26         if(c == 'n')
27             break;
28     }
29 
30     for(vector<Derivative>::iterator it = derivatives.begin();it != derivatives.end();++it)
31     {
32          if((*it).time != 0)
33         {
34             (*it).ratios *= (*it).time;
35             (*it).time--;
36             cout << (*it).ratios << " " << (*it).time;
37             if((*it).time != 0 && it != derivatives.end()-1)
38                 cout << " ";
39         }
40         if(it == derivatives.begin() && (*it).time == 0)
41         {
42             cout << "0 0";
43         }
44     }
45     return 0;
46 }

只有在每组结束后输出空格的代码不同。

 最终的代码:

 1 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 
 6 struct Derivative
 7 {
 8     int ratios;//系数
 9     int time;//次数
10 };
11 
12 int main()
13 {
14     int ratios;
15     int time;
16 
17     //接收输入
18     vector<Derivative> derivatives;
19     while(cin >> ratios >> time)
20     {
21         Derivative d;
22         d.ratios = ratios;
23         d.time = time;
24         derivatives.push_back(d);
25         char c = cin.get();
26         if(c == 'n')
27             break;
28     }
29 
30     for(vector<Derivative>::iterator it = derivatives.begin();it != derivatives.end();++it)
31     {
32         //次数不为0时,就输出经过处理的系数和指数
33         if((*it).time != 0)
34         {
35             if(it != derivatives.end() && it != derivatives.begin())
36                 cout << " ";
37             (*it).ratios *= (*it).time;
38             (*it).time--;
39             cout << (*it).ratios << " " << (*it).time;
40         }else if((*it).time == 0 && it == derivatives.begin())
41         {
42             //第一项的次数就为0时,直接输出0 0
43             cout << "0 0";
44         }
45     }
46 
47 
48     return 0;
49 
50 }

 

原文链接: https://www.cnblogs.com/apprendre-10-28/p/12746609.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++一元多项式求导

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/343516

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午2:09
下一篇 2023年3月2日 上午2:09

相关推荐