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

Writing a program that fills an array of 100 integers from 1 to 100

本文关键字:填充 整数 100个 数组 程序 一个      更新时间:2023-10-16

所以我有一个小问题。我只是不知道我做得对不对。这个问题很含糊。(对我来说)我想知道我是否能得到一些帮助,因为我在书中处理这个简单的问题已经两个小时了,它让我很失望!提前感谢:)

编写一个程序,用1到100的数字填充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<<"nn The Sum is " << sum << "n";
cout <<"n The Average is "<< avg << "n";

cout<<"nnn";
system ("pause");
return 0;
}

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

int arr[] = new int[100];

然后将其填充到for循环中,例如使用

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

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

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

一个可以做你想要的事情的示例程序是:

#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;
}  
#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;
}