C++我可以在这里使用数组来缩短代码吗

C + + Can I use arrays here to shorten my code?

本文关键字:代码 数组 我可以 在这里 C++      更新时间:2023-10-16

这是我在这里的第一篇帖子,所以请不要因为我的愚蠢而杀了我。

我最近做了一个有趣的程序,输入大量的数字,并让它显示平均值,这不是很有用,但我想我会看看是否可以。如果有人能向我解释我如何使用数组而不是大量变量来改进代码,但仍然可以实现同样的效果,甚至可能更高效,我会很高兴。

我的代码如下:

#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
    int q1;
    int q2;
    int q3;
    int q4;
    int q5;
    int q6;
    int q7;
    int q8;
    int q9;
    int q10;
    int q11;
    int q12;
    int f;
    //Used for the total of all values
    int t;
    //Used for the total to be divided
    int a;
    //Used for dividing the numbers.
    cout << "We will be finding a mean. Enter the amount of numbers that will be        entered, the maximum is 12: ";
    cin >> a;
    cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
    cin >> q1;
    cin >> q2;
    cin >> q3;
    cin >> q4;
    cin >> q5;
    cin >> q6;
    cin >> q7;
    cin >> q8;
    cin >> q9;
    cin >> q10;
    cin >> q11;
    cin >> q12;
    f = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12;
    cout << f / a << 'n';

    system("pause");
}

非常感谢您的任何建议!这是在Visual Studio中制作的,以备您需要了解。

当然,数组可以让您的生活更轻松!

以下是如何使用数组完成与上面相同的任务:

#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
    int totalNums;
    cout << "We will be finding a mean.n";
    cout << "You can only enter up to 12 numbers;
     // Declare an array to hold 12 int's
    int nums[12];
    // i will count how many numbers have been entered
    // sum will hold the total of all numbers
    int i, sum = 0;
    
    for(i = 0; i < 12; i++) {
        cout << "Enter the next number: ";
        cin >> nums[i];
        sum += nums[i];
    }    
    cout << "The mean is: " << (sum / totalNums) << 'n';

    //Try to avoid using system!
    system("pause");
}

但是,为什么要使用数组呢

在将数字添加到总数后,不需要保留任何数字,那么为什么要使用数组呢?

您可以在没有数组的情况下完成相同的任务,并且只使用一个数字变量!

#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
    int totalNums;
    cout << "We will be finding a mean.n";
    cout << "Enter the amount of numbers that will be entered: ";
    cin >> totalNums;
    // i will count how many numbers have been entered
    // sum will hold the total of all numbers
    // currentNum will hold the last number entered
    int i, sum = 0, currentNum = 0;
    
    for(i = 0; i < totalNums; i++) {
        cout << "Enter the next number: ";
        cin >> currentNum;
        sum += currentNum;
    }    
    cout << "The mean is: " << 1.0 * sum / totalNums << 'n';

    //Try to avoid using system!
    system("pause");
}

数组可以被视为一系列变量,每个变量都有id。介于0和(元素数)-1(包括两者)之间的整数是可用的id。

将其与循环一起使用,您的代码可以是这样的(对不起,我讨厌stdafx.h):

#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
    int q[12];
    int f;
    //Used for the total of all values
    int t;
    //Used for the total to be divided
    int a;
    //Used for dividing the numbers.
    cout << "We will be finding a mean. Enter the amount of numbers that will be        entered, the maximum is 12: ";
    cin >> a;
    cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
    for (int i = 0; i < 12; i++) {
        cin >> q[i];
    }
    f = 0;
    for (int i = 0; i < 12; i++) {
        f += q[i];
    }
    cout << f / a << 'n';
    system("pause");
}

您可以在将来使用读取的数字,但目前除了计算和之外,不使用这些数字,因此您可以省略数组并在读取时进行加法。此外,我删除了未使用的变量t,并停止使用using namespace std;,这被认为不太好。

#include <cstdlib>
#include <iostream>
using std::cin;
using std::cout;
int main() {
    int q;
    int f;
    //Used for the total of all values
    int a;
    //Used for dividing the numbers.
    cout << "We will be finding a mean. Enter the amount of numbers that will be        entered, the maximum is 12: ";
    cin >> a;
    cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
    f = 0;
    for (int i = 0; i < 12; i++) {
        cin >> q;
        f += q;
    }
    cout << f / a << 'n';
    system("pause");
}

您将这个问题标记为C++。

我建议您不要使用"using",您应该更喜欢向量而不是数组。

考虑以下方法:

#include <iostream>
#include <vector>
int main(int argc, char* argv[]) 
{
   std::cout << "We will be finding a mean." << std::endl
             << "Enter numbers, and press ^d when complete.n" 
             << std::endl;
   // Declare a vector to hold user entered int's
   std::vector<int> intVec;
   // the vector automatically keeps track of element count
   do {
      std::cout << "number: ";   // prompt
      int t = 0;
      std::cin >> t;             // use std::cin, 
      if(std::cin.eof()) break;  // ^d generates eof()
      intVec.push_back(t);
   }while(1);
   // there are several way to sum a vec, 
   // this works fine:
   int sum = 0;
   for (auto i : intVec)  sum += i;
   std::cout << "n  sum : " << sum
             << "ncount : " << intVec.size()
             << "n mean : " << (sum / intVec.size()) << std::endl;
   return(0);
}    

您可以每行输入一个项目(整洁度计数)。

您可以输入多个用空格分隔的整数,但上面会提示您输入已输入的整数。

^d-生成文件结尾输入
…同时按住"Control"键和字母"d"

注意-不处理错误输入-请尝试输入"number"作为"num"字符串。

公认的答案肯定是使用数组转换代码的最有效方法,但我要补充的一点是,在C++中,用一个整数除以另一个整数只能得到一个整数,因为你试图得到平均值,所以你似乎希望得到以小数为单位的结果,所以你需要做两件事之一:

  1. sum声明为浮子,以便将其除以totalNums以获得平均值
  2. 将其中一个整数强制转换为浮点或双精度,这样小数就不会被截断,所以最后一个cout语句看起来是这样的:

cout << "The mean is: " << (double)sum/totalNums << endl;

在C++中,精度的默认值为6,但您可以通过添加#include <iomanip>并使用iomanip中的setprecision( )函数来更改显示的小数点数量,您只需在同一输出行中添加即可:

cout << setprecision(x) << "The mean is: " << (double)sum/totalNums << endl;

其中x是你想要的任何精度。


如果你想尝试使用动态内存

这对你正在做的事情来说绝对不是必要的,但这是有趣的事情和良好的实践!

还有一件事是,如果你想让用户无限期地输入整数,你可以在运行时通过声明一个指向整数的指针数组(所以它是一个地址位置数组,而不是整数数组)和一些重要值来动态分配内存,这样他们就可以决定何时停止。该代码看起来像:

#include <iostream>
#include <iomanip>
using namespace std;
main( ) {
    const int ARRAY_SIZE = 200;
    const int SENTINAL = -999;
    int totalNums = 0;
    int sum = 0;
    //declare an array of pointers to integers so
    //the user can enter a large number of integers
    //without using as much memory, because the memory
    //allocated is an array of pointers, and the int
    //aren't allocated until they are needed
    int *arr[ARRAY_SIZE];
    cout << "We will be finding a mean." << endl;
    cout << "Enter integers (up to 200) or enter -999 to stop" << endl;
    //add a conditional into the for loop so that if the
    //user enters the sentinal value they will break out
    //of the loop
    for (int c = 0; c < ARRAY_SIZE; c++) {
        //every time you iterate through the loop, create a new
        //integer by using the new keyword using totalNums as
        //the index
        arr[totalNums] = new int;
        cout << "Enter integer: ";
        //input into the array of pointers by dereferencing it
        //(so it refers to what the pointer is pointer to instead
        //of the pointer)
        cin >> *arr[totalNums];
        if (*arr[totalNums] == SENTINAL)
            break;
        else {
            sum += *arr[totalNums];
            totalNums++;
        }
    }
    cout << setprecision(3) << "The mean is: " << (float)sum / totalNums << endl;
}
相关文章: