返回列表 發帖

[作業] 函式的建立與執行 (七) - 計算次方

本帖最後由 鄭繼威 於 2023-9-15 20:18 編輯

手工打造一個可計算次方的程式,不可使用pow()函式
//x的y次方=>x乘以y次
  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<ctime>
  4. using namespace std;

  5. int myPow(int a,int b)
  6. {
  7.         int sum=1;
  8.         for(int i=1;i<=b;i++)
  9.     {
  10.         sum=sum*a;
  11.     }
  12.     return sum;
  13. }

  14. int main()
  15. {
  16.    
  17.     int a,b;
  18.    
  19.     cout<<"請輸入你的底數:";
  20.     cin>>a;
  21.     cout<<"請輸入你的指數:";
  22.     cin>>b;
  23.    
  24.           
  25.    
  26.     cout<<a<<"的"<<b<<"次方:"<<myPow(a,b)<<endl;
  27.                
  28.     system("pause");
  29.     return 0;
  30. }
複製代碼
[進階! 遞迴]
  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<ctime>
  4. using namespace std;

  5. int myPow(int a,int b)
  6. {
  7.         if(b==1)
  8.         {
  9.                 return a;
  10.         }
  11.     return a*myPow(a,b-1);
  12. }

  13. int main()
  14. {
  15.    
  16.     int a,b;
  17.    
  18.     cout<<"請輸入你的底數:";
  19.     cin>>a;
  20.     cout<<"請輸入你的指數:";
  21.     cin>>b;
  22.    
  23.     cout<<a<<"的"<<b<<"次方:"<<myPow(a,b)<<endl;
  24.                
  25.     system("pause");
  26.     return 0;
  27. }
複製代碼

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

此帖僅作者可見
Attention seeker 101!

TOP

此帖僅作者可見

TOP

返回列表