C ++梯度函数返回假值

时间:2018-10-17 08:27:28

标签: c++

用户将输入4个不同的点,findSlope(函数)将计算坡度的值,并返回该值作为主函数中的cout。

但是当我运行程序时,它的斜率值出现逻辑错误。知道为什么吗?

#include <iostream>
#include <iomanip>
using namespace std;

float findSlope(float a,float b,float c,float d)
{
    return (d-b/c-a);
}   
int main()
{
    float slope,p1,q1,p2,q2;

    cout << "Enter x1: ";
    cin >> p1;
    cout << "Enter y1: ";
    cin >> q1;
    cout << "Enter x2: ";
    cin >> p2;
    cout << "Enter y2: ";
    cin >> q2;

    slope=findSlope(p1,q1,p2,q2);
    cout << "Point1" << "\t\tPoint2" << "\t\tSlope" << endl;
    cout << fixed << setprecision(2) << p1 << "," << q1 << "\t" << p2 << "," << q2 << "\t" << slope << endl;

    return 0;
}

2 个答案:

答案 0 :(得分:3)

  

return (d-b/c-a);

请再次查看操作顺序。您打算计算的是(d-b)/(c-a)。现在,您正在计算d - (b/c) - a。这是一门基本的数学知识,如果您自己检查一下,计算器很可能会给您相同的输出。

答案 1 :(得分:3)

您的坡度功能具有

class TrainValTensorBoard(TensorBoard):
    def __init__(self, log_dir='./logs', **kwargs):
        # Make the original `TensorBoard` log to a subdirectory 'training'
        training_log_dir = os.path.join(log_dir, 'training')
        super(TrainValTensorBoard, self).__init__(training_log_dir, **kwargs)

        # Log the validation metrics to a separate subdirectory
        self.val_log_dir = os.path.join(log_dir, 'validation')

    def set_model(self, model):
        # Setup writer for validation metrics
        self.val_writer = tf.summary.FileWriter(self.val_log_dir)
        super(TrainValTensorBoard, self).set_model(model)

    def on_epoch_end(self, epoch, logs=None):
        # Pop the validation logs and handle them separately with
        # `self.val_writer`. Also rename the keys so that they can
        # be plotted on the same figure with the training metrics
        logs = logs or {}
        val_logs = {k.replace('val_', ''): v for k, v in logs.items() if k.startswith('val_')}
        for name, value in val_logs.items():
            summary = tf.Summary()
            summary_value = summary.value.add()
            summary_value.simple_value = value.item()
            summary_value.tag = name
            self.val_writer.add_summary(summary, epoch)
        self.val_writer.flush()

        # Pass the remaining logs to `TensorBoard.on_epoch_end`
        logs = {k: v for k, v in logs.items() if not k.startswith('val_')}
        super(TrainValTensorBoard, self).on_epoch_end(epoch, logs)

    def on_train_end(self, logs=None):
        super(TrainValTensorBoard, self).on_train_end(logs)
        self.val_writer.close()

你的意思是

return (d-b/c-a)

运算符优先级将首先进行除法,而无需括号。