如何获得过程/函数值进入最终程序

How to get process/function values into the final program?

本文关键字:程序 何获得 过程 函数      更新时间:2023-10-16

所以,我得到了一个代码,我需要用x,y,a在程序中表达我的答案,通过编译,我只得到计算答案-整个循环中有y值的1列[5]。我怎么把它变成一个有x, y, a列和它们的值的表?我需要另一辆自行车吗?欢迎提出任何建议。

#include < iostream>
using namespace std;
float fy(float x, float a);
int main()
{
float a[5] = { -8, -6, -4, -2, 0 }
float y = 0;
int i = 0;
for (float x = -1; x <= 1; x += 0.5)
{
    cout << fy(x, a[i]) << endl;
    i++;
}
cin.get();
return 0;
}
float fy(float x, float a)
{
float y = 0;
if (sin(x)*a > 0)
    y = sqrt(sin(x)*a);
else
    cout << "no solutionn";
return y;
}

我猜你想要的是这样的:

x       y           a
-1      2.59457     -8
-0.5    1.69604     -6
0       -nan        -4
0.5     -nan        -2
1       -nan        0

对吧?

下面的代码可以完成这项工作:

#include <iostream>
#include <math.h>
using namespace std;
float fy(float x, float a);
int main() {
  float a[5] = {-8, -6, -4, -2, 0};
  float y = 0;
  int i = 0;
  cout << "x"
       << "t"
       << "y"
       << "t"
       << "a" << endl;
  for (float x = -1; x <= 1; x += 0.5)
  {   
    cout << x << "t" << fy(x, a[i]) << "t" << a[i] << endl;
    i++;
  }
  cin.get();
  return 0;
}
float fy(float x, float a) {
  float y = 0;
  if (sin(x) * a > 0)
    y = sqrt(sin(x) * a);
  else
    y = sqrt(-1);
  return y;
}

代码中的问题是您只打印函数的结果。所以既不输出x也不输出a[i]的值。检查替换的cout行,您将看到如何打印其他值。