【发布时间】:2016-02-11 01:48:48
【问题描述】:
我在处理这个问题时遇到了问题。它说当用户输入最小范围和最大范围时,我已经让程序找到最小值、最大值和范围。
这是我的代码:
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#define pi 3.1416
#define POINTS 20
using namespace std;
int main()
{
int Xmin, Xmax;
double step;
cout << "Enter a value for xMin and xMax:\n";
cin >> Xmin >> Xmax;
step = (double)(Xmax - Xmin) / (double)POINTS;
cout << "X-VALUES " << "" << "| " << "" << "Y-VALUES" << endl;
cout << "_________" << "" << "|_" << "" << "_________" << endl;
for (int i = 0; i < POINTS; ++i)
{
double x = Xmin + (step * i);
double y = 0.0572 * cos(4.667 * x) + 0.0218 * pi * cos(12.22 * x);
cout << x << "\t " << setprecision(2) << y << endl;
}
cout << "____________________" << endl;
return 0;
}
我这里是我的程序的输出:
X-Value | Y-Value
__________|__________
-2 -0.0043
-1.8 -0.0982
-1.6 0.0378
-1.4 0.0438
-1.2 0.0099
-1 0.0618
-0.8 -0.1118
-0.6 -0.0198
-0.4 -0.0047
-0.2 -0.0184
0 0.1257
0.2 -0.0184
0.4 -0.0047
0.6 -0.0198
0.8 -0.1118
1 0.0618
1.2 0.0099
1.4 0.0438
1.6 0.0738
1.8 -0.0982
2 -0.0043
─────────────────────
基本上,这个程序已经准备好了,有一个公式可以计算数字并根据用户输入的 Xmin 和 Xmax 列出它们。我假设让程序找到最小值、最大值,并根据上表中的 Y 值计算它的范围。
这是我查找最小值和最大值的代码。
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <limits>
#define pi 3.1416
#define POINTS 20
using namespace std;
int main()
{
int Xmin, Xmax;
double step;
int max = numeric_limits<int> :: min();
int min = numeric_limits<int> :: max();
int num = 0;
cout << "Enter a value for xMin and xMax:\n";
cin >> Xmin >> Xmax;
step = (double)(Xmax - Xmin) / (double)POINTS;
cout << "X-VALUES " << "" << "| " << "" << "Y-VALUES" << endl;
cout << "_________" << "" << "|_" << "" << "_________" << endl;
for (int i = 0; i < POINTS; ++i)
{
double x = Xmin + (step * i);
double y = 0.0572 * cos(4.667 * x) + 0.0218 * pi * cos(12.22 * x);
//printf(" %f\t%f\n ", x, y);
cout << x << "\t " << setprecision(2) << y << endl;
}
cout << "____________________" << endl;
while (cout << "Enter a value for xMin and xMax:\n" &&
cin >> Xmin >> Xmax)
{
if (num > max) max = num;
if (num < min) min = num;
}
cout << "max is: " << max << '\n'
<< "min is: " << min << '\n';
return 0;
}
它会运行,但不会打印出最小值或最大值。它只是在“输入 Xmin 和 Xmax”处重复程序。但是当我输入任何字母时,它会打印出最小值和最大值。帮我。我很困惑。
【问题讨论】:
-
将值存储在数组中,并尽可能使用标准算法来计算所需的输出(例如,
std::minmax_element、std::nth_element(中位数)、std::accumulate(均值) ) -
关于错误:我不知道您认为您的程序在做什么,但编译器会告诉您确切的问题:您正在从
num读取而没有将其初始化为值。 -
while (cout << "Enter a value for xMin and xMax:\n" && cin >> Xmin >> Xmax)认真的吗? -
我不明白你的评论
标签: c++