【发布时间】:2022-12-09 18:43:09
【问题描述】:
我开发了一个程序,将给定的区间 [a;b] 以 c 的步长制成表格,并在这个区间上找到它的最大值和最小值。我不确定我是否做对了,所以我想要一些建议。此代码有任务条件图片enter image description here
在求解给定问题的过程中,应用循环算子有一个前提条件。在执行给定任务的过程中,假设函数的参数标识为x,负责函数值的变量标识为y。
#include <iostream>
#include <math.h>
#include <clocale>
#define _USE_MATH_DEFINES
#include <iomanip>
#include<climits>
using namespace std;
int main(){
setlocale(LC_CTYPE, "");
double x, y, a, b, c;
double max, min, max_y, min_y;
max = -INT_MAX;
min = INT_MAX;
cout << "\n a:";
cin >> a;
cout << "\n b:";
cin >> b;
cout << "\n c:";
cin >> c;
cout << "\n a = " << a;
cout << " b = " << b;
cout << " c = " << c;
y = a;
while(y <= b){
if(y > 1) x = sin(sqrt(y + log(y)));
if((0 <= y) && (y <= 1)) x = M_PI + pow(cos(y + 1.2), 2);
if(y < 0) x = y * log10(pow(y,2) +2) + M_PI;
if(x > max){
max = x;
max_y = y;
}
if(x < min){
min = x;
min_y = y;
}
cout << "\n x = " << setw(8) << x << " y = " << setw(8) << y;
y += c;
}
cout << "\n The largest value in the given interval is" << max << " at y = " << max_y << "\n";
cout << "\n The smallest value in the given interval is" << min << " at y = " << min_y << "\n";
return 0;
}
当在控制台中输入值 a、b、c 时,我们的程序应该将函数制表(输出到控制台)并找到区间中的最小值和最大值。我的程序可以运行,但我不确定它是否正确。我想听听一些建议
【问题讨论】:
-
尽量避免
using namespace std,这是一个坏习惯。std::前缀的存在是有原因的。 -
更喜欢使用
(x * x)而不是pow(x, 2)。乘法通常更快更准确。 -
一旦您测试了该程序并确信它可以正常工作,您可以通过Code Review 寻求改进建议。我链接到请求帮助页面,因为您需要阅读它们以确保您满足他们对问题的期望。
-
@user4581301 谢谢
-
你为什么不确定它是否正确?使用不同的工具来绘制函数,您就会看到。我喜欢wolframalpha.com。如果您阅读了一些文档,您甚至可以使用它直接获取最小值/最大值
标签: c++