2017-09-24 48 views
-1

我想在C中編譯一個程序來返回數字的平方,例如1^2 = 1,但程序編譯時沒有問題,總是返回值爲0.在C中的平方問題#

我做錯了什麼?

#include <stdio.h> 
#include <math.h> 

int main(int argc, const char * argv[]) 
{ 
/* Define temporary variables */ 
double value1, value2; 
double result; 

/* Assign the values we will use for the pow calculation */ 
value1 = 0; 
value2 = 0; 

/* Calculate the result of value1 raised to the power of value2 */ 
result = pow(value1, value2); 

/* Display the result of the calculation */ 
printf("%f raised to the power of %f is %f\n", value1, value2, result); 

return 0; 
} 
+0

頂部的描述表明它只適用於正方形。你可以很容易地完成,只需要將它乘以沒有pow()函數的自己。此外,如果它的0,那麼你有問題設置變量....顯然,描述已不存在...但它是。 –

+0

@ M.Jameson請檢查我的答案 – GeneCode

回答

0

你可以計算指數或功率POW功能:

#include <math.h> 
double pow(double x, double y); 
0

它是一種簡單的錯誤。您忘記撥打[mySquare setPowering];功能。還有,你將一些未曾使用過的奇怪東西傳遞給該函數,所以我將其刪除了。

這是您的固定代碼。雖然下一次你應該在詢問我們之前仔細梳理你的代碼。否則,你不會學習重要的調試技巧。造成這種情況的最好方法是通過線只是字面上走線,並確保一切都被正確使用......這就是我如何發現錯誤:)

#import <Foundation/Foundation.h> 
#import <math.h> 

@interface Square: NSObject 
{ 
    int Constant; 
    int Power; 
    int Powering; 
} 
-(void) print; 
-(void) setConstant: (int) c; 
-(void) setPower: (int) p; 
-(void) setPowering; // <-- HERE 
@end 
@implementation Square 
-(void) print 
{ 
    NSLog (@"%i", Powering); 
} 
-(void) setConstant: (int) c 
{ 
    Constant = c; 
} 
-(void) setPower: (int) p 
{ 
    Power = p; 
} 
-(void) setPowering // <-- HERE 
{ 
    NSLog (@"%i^%i", Constant, Power); // This is optional 

    Powering = pow(Constant,Power); 
} 
@end 
int main (int argc, const char * argv[]) 
{ 
    Square *mySquare; 
    mySquare = [Square alloc]; 
    mySquare = [mySquare init]; 
    [mySquare setConstant: 2]; 
    [mySquare setPower: 3]; 
    [mySquare setPowering]; // <-- HERE 
    NSLog (@"The value of myPower is:"); 
    [mySquare print]; 

    return 0; 

} 
0

基於您的代碼:

[mySquare setConstant: 2]; 
[mySquare setPower: 3]; 
NSLog (@"The value of myPower is:"); 
[mySquare print]; 
  1. 我想你需要致電[mySquare setPowering]進行計算。

  2. [mySquare print]對我而言是新的。這是試圖打印課程?我認爲這很奇怪。我想你應該打印mySquare.Powering來檢查值。嘗試類似於

    NSLog("Powering: %d",mySquare.Powering); 
    
  3. 不確定爲什麼要將INT用於浮點計算。這也可能會影響我的結果。最好爲所有變量使用float。

這就是我所有的評論。