【问题标题】:C++: Buoyancy program does not output as plannedC++:浮力程序未按计划输出
【发布时间】:2014-10-19 03:22:51
【问题描述】:

我尝试编写一个程序,要求输入球体的半径和球体的重量。它使用这些输入来计算球体的浮力,然后程序确定它是否可以漂浮在水中。但是,无论我的输入是什么,我都会不断收到“6.95207e-308”

这些是编程作业的说明:

“浮力是物体漂浮的能力。阿基米德原理 表明浮力等于流体的重量 被淹没的物体所取代。浮力可以是 计算者:

浮力=(物体体积)乘以(流体的比重)

如果浮力大于或等于物体的重量 物体就会浮起来,否则就会下沉。

编写一个程序,输入重量(磅)和半径(磅) 球体的英尺)并输出球体是下沉还是漂浮 水。使用 62.4 磅/立方英尺作为水的比重。这 球体的体积是由 (4/3)π 乘以半径的立方计算的。"

这是我的代码:

//Written by: Edward Santiago
//Assignment: HW_03_No14.cpp
//Class: CO SCI 243
//Date: October 17, 2014
//Description: Prime Numbers
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
double sphere_volume (double);
double buoy_force (double,double);
int main ()
{

    double rad,volume,force,buoyancy;
    double weight;
    double water = 62.4;
    cout << "~~Buoyancy calculator~~" << endl;
    cout << "Please enter the radius of your sphere" << endl;
    cin >> rad;
    cout << "Please enter the weight of your sphere" << endl;
    cin >> weight;
    volume = sphere_volume(rad);
    buoyancy = buoy_force(volume,weight);
    cout << "The force of your sphere is "<<force<<endl;
    if (force <= water)
        cout << "Your sphere will float in the water"<<endl;
    else
        cout <<"Your sphere will sink :( "<<endl;
    return 0;
}
double sphere_volume (double radius)
{
    double vol;
    vol = ((4/3) * (M_PI) * (pow(radius,3)));
    return vol;
}
double buoy_force (double vol,double weight)
{
    double force;
    force = vol * weight;
    return force;
}

【问题讨论】:

  • 你应该启用警告,它会通知你这个问题。对于 gcc/clang 使用 -Wall -Wextra.

标签: c++ function exponent


【解决方案1】:

你永远不会初始化力。

buoyancy = buoy_force(volume,weight);
cout << "The force of your sphere is "<<force<<endl;

将分配更改为force = buoy_force(volume, weight)

【讨论】:

  • 您忘记在音量中添加“l”,但它现在可以使用。谢谢
【解决方案2】:

您将大答案分配给“浮力”,然后打印出“力”。

【讨论】:

    【解决方案3】:

    添加

    force=buoyancy; 
    

    就在打印force 之前。这是因为force 未初始化,您正在尝试打印它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 2017-11-17
      相关资源
      最近更新 更多