2011-03-31 66 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