C++ 为什么我的程序可以';你跑错了吗?
//计算一组整数的四分之一C++ 为什么我的程序可以';你跑错了吗?,c++,C++,//计算一组整数的四分之一 #include <iostream> #include <vector> #include <algorithm> #include <conio.h> using std::cin; using std::cout; using std::endl; using std::vector; using std::sort; int main() { // Ask for a set of integers co
#include <iostream>
#include <vector>
#include <algorithm>
#include <conio.h>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::sort;
int main()
{
// Ask for a set of integers
cout << "Please input a set of integers: "
<< endl;
// Read the set of integers
// x is the variable to write
int x;
// int_set is the set of integers to write
vector<int> int_set;
while (cin >> x)
{
int_set.push_back(x);
}
// Check if the integer set is vacant
typedef std::vector<int>::size_type vec_sz;
vec_sz size = int_set.size();
if (size == 0)
cout << "There are no data. "
<< "Please try again. ";
// Sort
sort (int_set.begin(), int_set.end());
// The set of integers multiply 1/4
vector<double> int_set_quarter;
cout << "The quarters of the set of integers are: ";
for (int i = 0; i != size; ++i)
{
int_set_quarter[i] = 1/4 * int_set[i];
cout << int_set_quarter[i];
cout << endl;
}
getch();
return 0;
}
#包括
#包括
#包括
#包括
使用std::cin;
使用std::cout;
使用std::endl;
使用std::vector;
使用std::sort;
int main()
{
//询问一组整数
库特(x)
{
内部设置。推回(x);
}
//检查整数集是否为空
typedef std::vector::size_type vec_sz;
vec_sz size=int_set.size();
如果(大小==0)
coutint\u set\u quarter
的大小为0,您可以在其上建立索引。
改变
<代码>向量int_set_4;quarty;
到
向量整数集四分之一(大小);
问题在于:
vector<double> int_set_quarter;
int_set_quarter[0] = 0.25;
您不能像使用
int\u set\u quarter
那样将元素添加到向量中,因此您最终会写入尚未分配的位置。这会导致访问冲突,并导致程序崩溃
您可以通过以下方式在向量中保留必要的空间:在提供所需元素的数量时,调用或,或使用将元素添加到向量的末尾
…或者,由于在循环后您不使用
int\u set\u quarter
执行任何操作,因此您只需将迭代需要输出的内容计算为局部变量,如所示。顺便说一句-如果您费心进行基本调试会话,您自己就会找到答案。@Eric:什么意思:如何解决它?如果你像我说的那样改变路线,一切都会好起来的。
vector<double> int_set_quarter(size);
vector<double> int_set_quarter;
int_set_quarter[0] = 0.25;
// The set of integers multiply 1/4
cout << "The quarters of the set of integers are: ";
for (int i = 0; i != size; ++i)
{
double quarter = 1/4 * int_set[i];
cout << quarter;
cout << endl;
}