定义的公式未正确转换

时间:2016-02-13 13:48:48

标签: python python-3.x

我正在尝试将输入的英制测量转换为公制,但转换不正确,我不知道为什么。 例如,组合总重量英制单位输入为50磅导致输出为17.72千克。 欢迎任何建议,评论或代码更改。 这是我的代码:

# Convert the total weight from Imperial, to Metric units
def convertWeight(totalWeight):
  return (totalWeight * 0.45359237)

# Calculate the cost of transport, by multiplying certain weight conditions by their respective cost per kilograms
def getRate(totalWeight):
  if totalWeight <= 2:
      rate = totalWeight * 1.10
  elif totalWeight > 2 and totalWeight <= 6:
      rate = totalWeight * 2.20
  elif totalWeight > 6 and totalWeight <= 10:
      rate = totalWeight * 3.70
  elif totalWeight > 10:
      rate = totalWeight * 4.20
  return rate

# Get the number of boxes
numBoxes = int(input('Please enter the number of boxes: '))
# Get the unit of measurement
unit = input('Please enter the unit of measurement, Imperial or Metric (as I or M): ')
# If the inputted unit of measurement does not equal one of these conditions, ask again for the unit of measurement, until one of these characters are inputted.
while unit not in ['I','M','i','m']:
   unit = input('Please enter the unit of measurement again, Imperial or Metric (as I or M): ')

totalWeight = 0
# For each box, get their respective weight
for x in range(numBoxes):
   weight = float(input('Please enter the weight of the boxes: '))
# Sum up the total weight by adding the inputted weights
   totalWeight = totalWeight + weight
# Does not work, check Parlas answers ; If the inputted unit is Imperial, convert it to Metric
   if unit in ['I', 'i']:
       totalWeight = convertWeight(totalWeight)
   else:
      totalWeight = totalWeight

# Calculate the transport cost, by calling the rate function
transportCost = getRate(totalWeight)
# Output the number of boxes, the total weight, and the transport cost to the user
print('The number of boxes is {0}, the total weight is {1:.2f} kilograms, and the transport cost is ${2:,.2f}.' .format(numBoxes, totalWeight, transportCost))

2 个答案:

答案 0 :(得分:0)

问题在于你的英制重量转换,

input

在get-weights循环中,

   if unit in ['I', 'i']:
       totalWeight = convertWeight(totalWeight)

因此,如果(例如)你有2个盒子,每个重25磅,公制重量应该是for x in range(numBoxes): weight = float(input('Please enter the weight of the boxes: ')) # Sum up the total weight by adding the inputted weights totalWeight = totalWeight + weight ,而是你在计算(25 + 25) * 0.4536

确保只有 后才能获得所有权重。

答案 1 :(得分:0)

我只是减少了缩进:

<?php
session_start();
include_once('header.php');
if(!$_SESSION['username'])
{

    header("Location: index.php");//redirect to login page to secure the welcome page without login access.
}
else
{
$user = $_SESSION['username'];

// Allow direct file download (hotlinking)?
// Empty - allow hotlinking
// If set to nonempty value (Example: example.com) will only allow downloads when referrer contains this text
define('ALLOWED_REFERRER', '');

// Download folder, i.e. folder where you keep all files for download.
// MUST end with slash (i.e. "/" )
define('BASE_DIR','../../downloads/');

// log downloads?  true/false
define('LOG_DOWNLOADS',true);

// log file name
define('LOG_FILE','downloads.log');

// Allowed extensions list in format 'extension' => 'mime type'
// If myme type is set to empty string then script will try to detect mime type
// itself, which would only work if you have Mimetype or Fileinfo extensions
// installed on server.
$allowed_ext = array (


  // documents
  'pdf' => 'application/pdf'
);



####################################################################
###  DO NOT CHANGE BELOW
####################################################################

// If hotlinking not allowed then make hackers think there are some server problems
if (ALLOWED_REFERRER !== ''
&& (!isset($_SERVER['HTTP_REFERER']) || strpos(strtoupper($_SERVER['HTTP_REFERER']),strtoupper(ALLOWED_REFERRER)) === false)
) {
 die("Internal server error. Please contact system administrator.");
}

// Make sure program execution doesn't time out
// Set maximum script execution time in seconds (0 means no limit)
//set_time_limit(0);

if (!isset($_GET['f']) || empty($_GET['f'])) {
  die("Please specify file name for download.");
}

// Nullbyte hack fix
if (strpos($_GET['f'], "\0") !== FALSE) die('');

// Get real file name.
// Remove any path info to avoid hacking by adding relative path, etc.
$fname = basename($_GET['f']);
if ($fname == $user."IN".".pdf")
{
// Check if the file exists
// Check in subfolders too
function find_file ($dirname, $fname, &$file_path) {

  $dir = opendir($dirname);

  while ($file = readdir($dir)) {
    if (empty($file_path) && $file != '.' && $file != '..') {
      if (is_dir($dirname.'/'.$file)) {
        find_file($dirname.'/'.$file, $fname, $file_path);
      }
      else {
        if (file_exists($dirname.'/'.$fname)) {
          $file_path = $dirname.'/'.$fname;
          return;
        }
      }
    }
  }

} // find_file

// get full file path (including subfolders)
$file_path = '';
find_file(BASE_DIR, $fname, $file_path);

if (!is_file($file_path)) {
  die("File does not exist. Make sure you specified correct file name.");
}

// file size in bytes
$fsize = filesize($file_path);

// file extension
$fext = strtolower(substr(strrchr($fname,"."),1));

// check if allowed extension
if (!array_key_exists($fext, $allowed_ext)) {
  die("Not allowed file type.");
}

// get mime type
if ($allowed_ext[$fext] == '') {
  $mtype = '';
  // mime type is not set, get from server settings
  if (function_exists('mime_content_type')) {
    $mtype = mime_content_type($file_path);
  }
  else if (function_exists('finfo_file')) {
    $finfo = finfo_open(FILEINFO_MIME); // return mime type
    $mtype = finfo_file($finfo, $file_path);
    finfo_close($finfo);
  }
  if ($mtype == '') {
    $mtype = "application/force-download";
  }
}
else {
  // get mime type defined by admin
  $mtype = $allowed_ext[$fext];
}

// Browser will try to save file with this filename, regardless original filename.
// You can override it if needed.

if (!isset($_GET['fc']) || empty($_GET['fc'])) {
  $asfname = $fname;
}
else {
  // remove some bad chars
  $asfname = str_replace(array('"',"'",'\\','/'), '', $_GET['fc']);
  if ($asfname === '') $asfname = 'NoName';
}

// set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mtype");
header("Content-Disposition: attachment; filename=\"$asfname\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);

// download
// @readfile($file_path);
$file = @fopen($file_path,"rb");
if ($file) {
  while(!feof($file)) {
    print(@fread($file, 1024*8));
    flush();
    if (connection_status()!=0) {
      @fclose($file);
      die();
    }
  }
  @fclose($file);
}

// log downloads
if (!LOG_DOWNLOADS) die();

$f = @fopen(LOG_FILE, 'a+');
if ($f) {
  @fputs($f, date("m.d.Y g:ia")."  ".$_SERVER['REMOTE_ADDR']."  ".$fname."\n");
  @fclose($f);
}
}
else
{
                  echo '<script type="text/javascript">alert("Access Violation !")header("Location: index.php");</script>';
}
}
?>

我以前的代码是转换每个单独的权重,然后将其添加到总数中,而不是仅仅转换总数... 菜鸟错误。