注册 登录
编程论坛 C++教室

请大家帮忙看看这个小程序错在哪了

vyzj 发布于 2009-10-23 17:22, 646 次点击
//返回数组的长度
#include<iostream>
using namespace std;

template<typename T,size_t N>
size_t size(T (&arr)[N])
{
    return N;
}


int main()
{
    int ia[] = {1,2,3,4,5,6,7};
    cout << size(ia) << endl;
   

    return 0;
}



[ 本帖最后由 vyzj 于 2009-10-23 18:04 编辑 ]
7 回复
#2
shl3052009-10-24 00:31
数组做参数只传首地址,长度是没办法确定的,即使如 int  func(int a[10]){...}  这样写10是没有意义的,写不写都一样
#3
gz812009-10-24 09:40
以下是引用shl305在2009-10-24 00:31:13的发言:

数组做参数只传首地址,长度是没办法确定的,即使如 int  func(int a[10]){...}  这样写10是没有意义的,写不写都一样
嗯,赞同。

lz想求数组的长度,直接这样就可以了:

#include<iostream>
using namespace std;

int main()
{
    int ia[] = {1,2,3,4,5,6,7};
    cout << sizeof(ia)/sizeof(int) << endl;
   

    return 0;
}
#4
flyingcloude2009-10-24 10:41
以下是引用gz81在2009-10-24 09:40:57的发言:

嗯,赞同。

lz想求数组的长度,直接这样就可以了:

#include<iostream>
using namespace std;

int main()
{
    int ia[] = {1,2,3,4,5,6,7};
    cout << sizeof(ia)/sizeof(int) << endl;
   

    return 0;
 ...
#5
苏洛离2009-10-24 19:41
cout << sizeof(ia)/sizeof(int) << endl; 这句可以改成 cout << sizeof(ia << endl; 吗?楼上的

#6
东西邪毒2009-10-24 22:24
回复 5楼 苏洛离
#include<iostream>
#include<string>
using namespace std;


class Student
{
   
private:
    string name;
    long unsigned int num;
    float score;
    static int k;
    static float averscore;
public:
    void input();
    void display();
    void averScore();
    static float printaverScore(){ return averscore;}
};

float Student::averscore = 0.0;
int Student::k = 0;



void Student::averScore()
{
    k++;
    averscore = (averscore + score) / (float) k ;
}
   


void Student::input()
{
    cout<<"Enter the name:\n";
    cin>>name;

    cout<<"Enter the number:\n";
    cin>>num;

    cout<<"Enter the score:\n";
    cin>>score;
}


void Student::display()
{
    cout<<name<<"\t\t"<<num<<"\t\t"<<score<<endl;
}
   
   


int main()
{
    Student stu[100];
    int i = -1;
    char ch = 'y';
    cout<<"Pls input the infomation of students"<<endl;


    do
    {
        i++;
        stu[i].input();
        stu[i].averScore();
        cout<<"[y/n?]"<<endl;
        cin>>ch;
   
    }while(ch == 'Y' || ch == 'y');

    cout<<"Name"<<"\t\t"<<"Number"<<"\t\t"<<"Score"<<endl;
    for(int j = 0;j<=i;j++)
        stu[j].display();

    cout<<"The average score of these students is: "<<Student::printaverScore()<<endl;

    return 0;



}
#7
cookies50002009-10-25 14:54
LZ,电脑不是人,它很傻的,你不抽鞭子叫它去遍历每个数组元素它不会主动给你返回一个N的.
#8
vyzj2009-10-25 16:28
好,谢谢大家
1