C++我可以在这里使用数组来缩短代码吗
C + + Can I use arrays here to shorten my code?
这是我在这里的第一篇帖子,所以请不要因为我的愚蠢而杀了我。
我最近做了一个有趣的程序,输入大量的数字,并让它显示平均值,这不是很有用,但我想我会看看是否可以。如果有人能向我解释我如何使用数组而不是大量变量来改进代码,但仍然可以实现同样的效果,甚至可能更高效,我会很高兴。
我的代码如下:
#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++中,用一个整数除以另一个整数只能得到一个整数,因为你试图得到平均值,所以你似乎希望得到以小数为单位的结果,所以你需要做两件事之一:
- 将
sum
声明为浮子,以便将其除以totalNums
以获得平均值 - 将其中一个整数强制转换为浮点或双精度,这样小数就不会被截断,所以最后一个
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;
}
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 请解释字谜的代码,我看不懂计数器数组,每个值已经是0
- 代码使用向量成功运行,但使用数组显示错误
- C++逗号分隔的输入数组代码过早退出
- 如何修改代码以打印出数组 v2
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 如何在 c# 代码中通过引用调用时从 c++ dll 更新数组值?
- 使用基于数组和范围的 For 循环替换一些基本代码行
- G++ 发出警告,要求删除一个代码的数组,但不删除另一个代码的数组
- 为什么我的代码在尝试复制字符数组时引发 C6386 错误?
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 调试代码块中的数组
- "p"数组如何使用 std::normal_distribution 存储以下代码中的值C++?
- 在带有模板的函数中传递未知大小的 std::数组.如何更正此代码?
- 有没有办法在c ++中清除空数组,请检查下面的代码以获取说明
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 我的旋转数组代码给出了大数组大小的错误
- 将字符数组转换为键代码数组 c++