C++三角形面积周长计算程序传入参数后仍输出垃圾值的原因排查
Let's walk through the issues in your code step by step—they're common pitfalls, so don't worry, fixing them is straightforward:
1. You're Passing Uninitialized Variables Instead of Using Your Class's Data
In your main() function, you declare int x, y, z; but never assign any values to them. When you call t1.Area(x, y, z) and t1.peri(x, y, z), you're passing these uninitialized variables (which hold random garbage values) instead of using the a, b, c values you already stored in your t1 object via t1.getdata().
Even worse, your peri() and Area() functions accept parameters, but you don't need them—your class already has a, b, c as member variables. You can rewrite these functions to use the class's internal data directly.
2. The Area() Function Has Two Critical Flaws
- It doesn't return a value: The function is declared as
float Area(...), but there's noreturn area;statement at the end. When you try to print its result inmain(), you're getting undefined garbage because the function doesn't properly return the calculated area. - Integer division messes up the semi-perimeter:
s = (a + b + c) / 2;uses integer division sincea,b,care integers. For example, if your sides sum to 9, this would give you4instead of the correct4.5, which breaks the Heron's formula calculation. You need to cast the sum to a float first to get a decimal result. - Unnecessary
coutinsideArea(): You're printing the area twice—once inside the function and once inmain(). Pick one place to avoid duplication.
Fixed Version of Your Code
Here's the corrected code with all these issues addressed:
#include <iostream> #include <cmath> // Removed <conio.h> since it's non-standard and not used here using namespace std; class Triangle { public: int a, b, c; void getdata(); // Rewrote to use class members instead of parameters int peri() { return a + b + c; } float Area() { // Cast sum to float to avoid integer division float s = static_cast<float>(a + b + c) / 2; float area = sqrt(s * (s - a) * (s - b) * (s - c)); return area; } }; void Triangle::getdata() { cin >> a >> b >> c; } int main() { cout << "Enter the three sides: "; Triangle t1; t1.getdata(); cout << "The area of that triangle is " << t1.Area() << " and the perimeter is " << t1.peri() << endl; return 0; }
Key Changes Explained
- Removed unused
<conio.h>header (it's not standard C++ and wasn't being used). - Modified
peri()andArea()to use the class's owna,b,cmembers instead of accepting external parameters. - Fixed the semi-perimeter calculation with
static_cast<float>to ensure floating-point division. - Added
return area;to theArea()function so it properly returns the calculated value. - Removed the redundant
coutinsideArea()to avoid duplicate output. - Cleaned up the output message in
main()for readability.
内容的提问来源于stack exchange,提问作者Noob_coder

