【发布时间】:2014-10-15 11:48:42
【问题描述】:
我是 C++ 编程的新手,在显示数组的内容时遇到了一些问题。该脚本非常简单,旨在绘制一个函数 f(x);基本上在我通过for循环创建数组(x_vect)之后。我想显示其中的内容而不在循环内执行(那将是作弊)。
// Grafico di una funzione
#include <iostream>
#include <stdio.h> // serve per poter utilizzare PRINTF e SCANF
#include <math.h>
using namespace std;
int main()
{
float x_in, x_fin; // estremi della funzione
float delta_x; // passo della funzione
int n; // numero di passi
// ciclo di controllo sugli estremi dell'intervallo
while (x_fin < x_in)
{
cout << endl;
printf("> Insert extreme values: ");
scanf("%f" "%f", &x_in, &x_fin); // NB: non va la virgola tra le %f
cout << endl;
printf("> number of intervals: ");
scanf("%d" , &n); // NB: %d se voglio avere un numero intero
if (x_fin < x_in)
{
cout << endl;
cout << "> Warnign: wrong extreme values (x_fin > x_in)" << endl;
}
}
delta_x = (x_fin - x_in)/n;
float x_vect[n];
float x = x_in;
x_vect[0]=x;
for (int i=1; i<n; i++)
{
x = x + delta_x;
x_vect[i] = x;
}
cout << x_vect << endl; // HERE'S THE PROBLEM !!!!!!!!!!!!!!!!!
// apertura del file per il salvataggio dei dati
FILE *file; // comando necessario per salvataggio di un file
file = fopen("salvataggio_dati.txt", "wt");
fclose(file);
cout << endl;
return 0;
}
但是脚本并没有获取 x_vect 的内容,而是返回一系列奇怪的字母和数字,例如:0x7fff4f6e4ec0
有什么想法吗?提前致谢。
【问题讨论】:
-
你正在打印你的数组的地址(这是
x_vect所指的),如果你想打印你需要循环的数组的内容 -
为什么在引用调用时期望得到内容?
-
您的代码看起来像 cout 行中的 C 代码部分。在 C++ 中有比 scanf 更好/更安全的选项
-
声明时您不会初始化
x_in和x_fin,然后比较它们(注意:初始值未定义)。您还可以使用float x_vect[n];。当n不是常量表达式时,这目前不是标准 C++ 的一部分(这在 C 中受支持并作为 GCC 扩展)。 -
至于您的“问”问题,您需要遍历数组以打印各个答案。实际上,您是在告诉代码打印数组开始的地址。您可能还可以考虑
std::vector。