C++ - 计算比萨中的切片数

men*_*dia -1 c++ visual-studio-2010

我编写了这个程序来计算给定的这种大小的比萨饼(直径)的切片数。但结果似乎有点偏离......任何帮助将不胜感激:)

例如:如果我输入 18 英寸的比萨,它会产生 4.00344 片……如果我输入 22 英寸的比萨,它会产生 4.8931 片……

见下面的代码:

    #include <iostream>
using namespace std;
int main()
{
    // Title of CMD Window
    system("title How many Slices are in your Pizza?");
    // Declare variables    
    double  diameter = 0.0,     // Diameter of the pizza
            slices = 0.0,       // No. of slices in the pizza
            area = 0.0,         // Area of the whole pizza
            oneSlice = 14.125;  // Area of one pizza slice
    const double PI = 3.14159;
    // Display prompt   
    cout << "What is the diameter of the pizza (inches):" << "\n";
    cin >> diameter;
    //  Calculate the area of the pizza
    area = PI * diameter;
    // Calculate number of slices for the size of pizza given
    slices = area / oneSlice;
    // Display results
    cout << "\n\n" << "You have " << slices << " slice(s) in this pizza:" <<  "\n\n"
         << "************************************" << "\n"
         << "\tDiameter of pizza= " << diameter << "\n"
         << "\tArea of pizza= " << area << "\n"
         << "************************************" << "\n";
    system("pause"); 
    return 0;
} 
// End of program
Run Code Online (Sandbox Code Playgroud)

Mar*_*k B 5

圆的面积不是pi * diameter:那是周长。

你需要 area = PI * (diameter / 2.0) * (diameter / 2.0);

  • 我认为当提出问题的人以“看起来有效”或类似的方式回应一个好的答案时,这是*这样的*一个不好的迹象。就像您想要的只是一个快速解决方案,您仍然不明白*为什么*您的方法不正确,而且您也不真正关心。 (3认同)