编写一个程序,填充100个整数的数组,从1到100

时间:2014-04-14 23:50:15

标签: c++ arrays integer

所以我对此有一个小问题。我只是不知道我是否正确地做到了。问题很模糊。 (对我而言)想知道我是否能得到一些帮助,因为我已经在我的书中遇到了这个简单的问题,现在已经有2个小时了,它让我感到震惊!在此先感谢:)

"写一个填充"填充"一个由100个整数元素组成的数组,数字从1到100,然后输出数组中的数字。"

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
const int size = 301;
int N, I, k;
int score[size];
srand(time(0));


cout   << setprecision(2)
       << setiosflags(ios::fixed)
       << setiosflags(ios::showpoint);

//1)Get # of bowlers ..............................................................
      cout << "Enter number of bowlers? (Must be between 1 and 301) ";
      cin >> N;
      while (N<1||N>size)
{
      cout << "\nError!! Must be between 1 and 301!! ";
      cin >> N;
}
//2) and 5)  Get scores ............................................................
for(I = 0; I<N; I++)
{
//cout << "\nEnter score for bowler # " << I + 1 << " ";
//cin >> score[I];
score[I]=rand()%301;

for(k=0; k<I; k++)
{
    if(score[k]==score[I])
    {
        I--;
        break;
    }

}
}

//3)Get Sum/Avg .....................................................................
int sum = 0;
float avg;
for(I = 0; I<N; I++)
{
sum += score [I];

}

avg = float(sum)/N;




//4) Output scores, sum, and avg ....................................................

for(I = 0; I<N; I++)
{
cout << "\nScore for bowler # " << I + 1 << " is  "  << score[I];

}
cout<<"\n\n The Sum is " << sum << "\n";
cout <<"\n The Average is "<< avg << "\n";


cout<<"\n\n\n";
system ("pause");
return 0;
}

3 个答案:

答案 0 :(得分:2)

代码的核心只需要创建数组,例如与

int arr[] = new int[100];

然后将其填入for循环,例如与

for (i = 0; i<100; i++) arr[i] = i+1;

请注意,数组索引从零开始计算,但您希望从一个开始填充。

答案 1 :(得分:0)

您确定代码与您的问题有关吗?

执行所需操作的示例程序是:

#include <stdlib.h>
#include <stdio.h>

#define N 100

int main(void)
{
        int arr[N], i;

        for (i = 0; i < N; i++)
                arr[i] = i + 1;

        for (i = 0; i < N; i++)
                printf("%d ", arr[i]);

        return 0;
}  

答案 2 :(得分:0)

#include <iostream>
#define NUM_VALUES 100

int main()
{
    int i = 1;
    int array[NUM_VALUES];

    while (i <= NUM_VALUES)
    {
        array[i-1] = i;
        i++;
    }

    i = 1;

    while (i <= NUM_VALUES)
    {
        std::cout << array[i-1] << " ";
        i++;
    }

    std::cout << std::endl;
    return 0;
}