簡體   English   中英

如何將過程/功能值輸入最終程序?

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

因此,我得到了一個代碼,我需要在程序中用x,y,a將我的答案表達為3列,通過編譯,我在整個循環中只得到計算答案-y值為1列[5]。 如何使用x,y,列及其值創建表格? 我需要另一個周期嗎? 任何建議表示贊賞。

#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 solution\n";
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]值。 檢查替換的提示行,您將看到如何打印其他值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM