2011-03-31 27 views
0

我無法編譯一些代碼,一類....
這就是我在遇到麻煩編制問題的數學LIB C++

aavg=0; int count=0; 
    for(int i=0; i<num;i++) 
    { 
    if ((math.abs(a[i])<25.0) 
    { 
count++; 
aavg+=a[i];        
    } 
    } 
aavg=aavg/count; 
cout << "The average a value in range, absolute value of a is less than 25.0 is: "<< aavg <<endl; 

這是我的整個程序

#include <iostream> 
    #include <fstream> 
    #include <math.h> 
    #include <cmath> 
    using namespace std; 
    int main (void) 
    { 
     ifstream input ("measurements"); 
     int num=0; 
     input >> num; 
     float a[num]; 
     float b[num]; 
     float c[num]; 
     for(int i=0; i<num;i++) 
     input >> a[i] >> b[i] >> c[i]; 
     //All DATA IN 
     //Do A AVERAGE 
     float aavg =0; 
     for(int i=0; i<num;i++) 
     aavg+=a[i]; 
     aavg=aavg/num; 
     cout << "A average: " << aavg <<endl; 
     //DO SMALLEST B 
     float smallb=b[0]; 
     for(int i=1; i<num; i++) 
     if(smallb>b[i]) 
     smallb=b[i]; 
     cout <<"Smallest b: " <<smallb <<endl; 
     //PRINT ALL GISMO NUMBERS WHERE "a+c<60.0 
      for(int i=0; i<num;i++) 
      if((a[i]+c[i])<60.0) 
     cout <<"Gismo number " <<i <<" has a and c values that total less than 60" <<endl; 
     //PRINT SMALLEST C VALUE BETWEEN 25.0 AND 50.0 
      float smallc=51; 
      for(int i=0; i<num;i++) 
      if((25.0<c[i])&&(c[i]<50)) 
      if(smallc>c[i]) 
      smallc=c[i]; 
      if(smallc>50) 
      cout <<"No values in range" <<endl; 
      else 
      cout <<"Smallest c in range was: "<<smallc <<endl; 
      //LAST PART! woot! 
      aavg=0; int count=0; 
     for(int i=0; i<num;i++) 
     { 
     if ((math.abs(a[i])<25.0) 
     { 
    count++; 
    aavg+=a[i];        
     } 
     } 
    aavg=aavg/count; 
    cout << "The average a value in range, absolute value of a is less than 25.0 is: "<< aavg <<endl; 
    //system("PAUSE"); 
    } 

回答

4
math.abs 

math不是一個對象,它是庫的名稱。

該函數只是std::abs(如果包含<cmath>)或abs(如果包含<math.h>)。您只需包含兩個標題中的一個。


你的程序還有其他一些問題。數組的大小必須是C++中的編譯時常量,因此您的a,bc的聲明無效。最簡單的做法是使用std::vector<float>std::vector是一個可以在運行時調整大小的容器。

儘管您的程序可能會作爲學習練習,但您應該始終檢查任何輸入操作以確保其成功。如果「測量」文件中的第一項是Hello,則首次提取將失敗。 num將保持0,您的程序將不會讀取任何進一步的輸入,並且您將最終除以零(aavg=aavg/num;)。您可以在the answers to another question中找到有關流錯誤標誌以及如何正確檢查輸入操作結果的更多信息。

+0

非常感謝。這對我來說。我感覺有點傻。 (我正在學習另一種語言的c ......這就是你如何完成abs – David 2011-03-31 03:47:43

+0

@David:你沒有學習C,你正在學習C++ – 2011-03-31 03:50:57

0

你有兩個問題。你強調的是一個表達式:

math.abs(a[i]) 

所有你想要的是:

fabs(a[i]) 

另一種是採用非const num作爲數組的大小。這不合法。您需要動態分配的陣列:

float* a = new float[num]; 
+0

另外,用你的'abs 'operation! – holtavolt 2011-03-31 03:48:25

+0

請注意,在C++中,'abs'使用浮點參數,因爲這是C++,'std :: vector'優於手動動態分配數組。 – 2011-03-31 03:55:00