2013-11-27 53 views
-5

請幫我解決這個X^Y:查找使用while語句

使用while語句編寫C++程序,提示用戶輸入兩個數字(X,Y),然後求出x ^年。

樣品試驗:

請輸入x和y

7^0 = 1

請輸入值的值的x和y

5^6 = 15625

P.S沒有POW聲明請。 我做了功率聲明(它很容易),但我需要它沒有pow的聲明 多數民衆贊成在我做了什麼

int counter,x,y,ttl; counter = 0;

while (counter == 0){ 
    cout << "Please enter the values of x and y "; 
    cin >> x >> y; 
    ttl = pow(x,y); 

    counter++; 
} 
cout << x << "^" << y << " = " << ttl ; 
+4

您好,歡迎計算器。 COM。請花些時間閱讀[幫助頁面](http://stackoverflow.com/help),尤其是名爲[「我可以問些什麼話題?」]的章節(http://stackoverflow.com/help/)討論話題)和[「我應該避免問什麼類型的問題?」](http://stackoverflow.com/help/dont-ask)。更重要的是,請閱讀[Stack Overflow問題清單](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist)。您可能還想了解[SSCCE](http://sscce.org/)是什麼。 –

+0

指數運算最簡單(但不是最快)的方法是重複乘法。使用循環重複乘法。如果您遇到任何具體問題,請提出有關它們的具體問題。 –

+0

未來的注意事項:在一個環境中可能具有某種含義的某些字符在另一個環境中可能具有不同含義。儘管在某些情況下插入符號(^)用於表示取冪,但在編程中,特別是在C++中,它表示'xor'。儘量至少在第一次使用時描述除最明顯的操作符之外的任何其他意圖。 –

回答

2

這裏有三個解決方案
(雖然第一次不使用while循環)

int power(int x, int y) 
{ 
    return (y==1) 
    ?x:x* 
    power(x, --y); 
} 

或者,如果你真的想要一個while循環:

int power(int x, int y) 
{ 
    while (y-1) 
    return x*power(x, --y); 
    return x; 
} 

如何使用 「雲間」:

int power(int x, int y) 
{ 
    int r = 1; 
    while (y --> 0) r *= x; return r; 
} 
1

由於user3041987指定while語句應該使用,也許我們其實可以寫的東西使用while循環:):

int power(int x, int y) 
{ 
    int result = 1; 
    int i = 0; 
    while(i<y) 
    { 
    result *= x; 
    ++i; 
    } 
    return result; 
} 
0

這應該做

int x,y,prod=1; 
cout<<"Please enter the values of x and y "; 
cin>>x>>y; 

while (y>0) 
{ 
prod*=x; 
y--; 
} 
cout<<x<<"^"<<y<<"= "<<prod; 
+0

我做了它使用POW #include #include using namespace std; int main() { \t int counter,x,y,ttl; \t counter = 0; \t while(counter == 0){ \t \t cout <<「請輸入x和y的值; \t \t cin >> x >> y; \t \t ttl = pow(x,y); \t \t counter ++; \t} \t cout << x <<「^」<< y <<「=」<< ttl; \t return 0; – Excalibur

+0

但老師說不要用pow :( – Excalibur

+0

@ user3041987:老師說「請讓堆棧溢出人羣爲你解決嗎?」 –