English 中文(简体)
简单平均数计算
原标题:Simple average calculation
  • 时间:2010-05-19 21:28:02
  •  标签:
  • c++
  • average

I m试图撰写计算一个阵列中特定数字平均数的方案。 数量不应超过100个,用户应当投入到这些数量,直到有以下变化:

#include <iostream>
#include <conio.h>
using namespace std;

double average(int tab[], int i){

    int sum=0;

    for(int j=0; j<i; ++j){
            sum+=tab[j];
    }
    return (double)sum/i;

}

int main()
{
    int tab[100];
    int n=0;   
    int number=0;


    do {
       if(n < 100){
           cout << "Give " << n+1 << " number : ";
           cin >> number;
           tab[n]=number;
           number=0;
           ++n;       
       }
       else{
            break;
       }
    } while( !isdigit(number) );      

    cout << average(tab, n) << endl;

    getch();
    return 0;
}

为什么在提供果园之后,它就印刷了我的Give n号:对我阵列的所有空囚室来说? 它只应使用特定数字。

最佳回答

http://www.un.org/Depts/DGACM/index_french.htm 测试只是在分配0到数字之后才能进行,0是一部控制法,不是数字,因此<条码>is 数(0)总是不实的,因此,尽管情况总是真实的。

 ...
       number=0;
 ...
} while( !isdigit(number) );      

相反,测试投入流,以确定其是否成功地阅读了价值。

int main()
{
    const size_t COUNT = 100;
    int tab[COUNT];
    size_t n;   

    cin.tie(&cout); // ensures cout flushed before cin read
    // (not required if your runtime complies with that part of the standard)

    for (n = 0; n < COUNT; ++n ) {
        cout << "Give " << n+1 << " number : ";
        cin >> tab[n];

        if (!cin)
            break;
    }

    if (n > 0) // average is undefined if n == 0
        cout << average(tab, n) << endl;

    return 0;
}
问题回答

页: 1 这里不正确——它用于测试<代码><>char>/code> 是数字的——你可以不使用该编号来测试某一条。

也许希望考虑使用特殊价值来终止投入,例如<代码>-1或-999。 如果不能接受,那么你就不得不在体力而非内心读,然后决定是否算数。

除了滥用本应使用某些发送装置的数位数之外,没有必要将数字储存在一阵列中。 计算平均数的操作额和数量足够。

此外,还应检查零件,以防止出现零差错。

#include <iostream> // <conio.h> is nonstandard
using namespace std;

int main() {
    long total = 0, cnt = 0, num;

    while ( cerr << "Enter " << ++ cnt << " number" << endl, // use cerr for interaction
              // use comma operator to produce a side effect in loop expression
            cin >> num ) { // use Boolean value of (cin >> ...) to end loop on input failure
        total += num; // just keep a running total
    }
    -- cnt; // cnt went one too far :(

    cout << static_cast<double>( total ) / cnt << endl;
}

检测非编号投入的更好方法是测试cin/code>的状况。 阅读价值后:

// ...
if (cin >> number)
{
  tab[n++] = number;
}
else
{
  break;  // break out of loop
}

人们还记得,除了不输入有效数目之外,其他原因可能失败。

贵国法典存在几个问题:

cin >> number;

如果溪流开采作业失败,你不作检查。 这样做的一个简单办法是利用operator void*(。 转换操作员:

if (cin >> number)
  ... operation succeeded ...

以上代码等于检查>failbitbadbit

页: 1 你再通过一个编号(例如1234,而不是一个特性(例如z )。 不管怎样,加上一个流层开采作业失败,就不必进行这种数字式检查。

您可使用<代码>lexical_cast。 你们阅读了插图中的投入,如果能够转换成插图,将进行校正。 这还将确保,如果你身边的号码是负数或数,就不会被长期改变。

#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using boost::lexical_cast;
using boost::bad_lexical_cast;

double average(int tab[], int i){

    int sum=0;

    for(int j=0; j<i; ++j){
            sum+=tab[j];
    }
    return (double)sum/i;

}

int main()
{

    int tab[100]; //this is a fairly low level construct which might want to
                  // into a std::vector 

    string input; 

    int n;
    try{
        for (n = 0 ;n < 100; n++) {
           cout << "Give " << n+1 << " number : ";
           cin >> input;                          //read number into string
           tab[n]= lexical_cast<int>(input);     //conversion with lexical_cast
                                                 //if not possible exception is 
                                                 //thrown
        }
     }
     catch(bad_lexical_cast &){
        cout << "not a number" << endl;
     } 

    cout << average(tab, n) << endl;

    return 0;
}

www.un.org/chinese/sc/presidency.asp 页: 1

因此(假定你正在使用ASCII),你可以简单地使用一种特性并测试其ASCII代码范围:

    int tab[100]; 
    int n = 0;    
    char c;

    while (n++ < 100)
    {
       cout << "Give " << n << " number : "; 
       cin >> c;
       if (c < 48 || c > 57)
          break;
       tab[n - 1] = c - 48;            
    }

    cout << average(tab, n - 1) << endl; 

    getch(); 
    return 0; 

也可使用<代码>cin.getline和atoistrtod:

int tab[100]; 
int n=0;    
int number=0; 
char input[10];

while (n++ < 100)
{     
   cout << "Give " << n << " number : ";
   memset(input, 0x00, 10);
   cin.getline(input, 10);
   number = atoi(input);
   if (number > 0)
      tab[n-1] = number; 
   else
      break;
}

cout << average(tab, n-1) << endl; 

getch(); 
return 0; 

然而,你可以采用其他方法,这些方法应当给你一些想法。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签