Pregunta

Ok so my .exe is giving me a zero so im guessing that the data type is not casting correctly. Sorry im new to c++ and came from c. Any time i had this problem in c something usually was truncated, but i cant find out what i did wrong.

//shape.h
#ifndef SHAPE_H
#define SHAPE_H
class shape 
{
public:
   shape();
   virtual float area()=0;

};

#endif SHAPE_H


//shape.cpp
#include <iostream>
#include "shape.h"
using namespace std;

shape::shape()
{
}

//triangle.h
#include"shape.h"

class triangle: public shape 
{
public: 
    triangle(float,float);
    virtual float area();
protected:
    float _height;
    float _base;


 };


//triangle.cpp
#include "triangle.h"

triangle::triangle(float base, float height)
{
base=_base;
height=_height;
}
 float triangle::area()
 {
return _base*_height*(1/2);
  }

//main.cpp
#include <iostream>
#include "shape.h"
#include "triangle.h"
using namespace std;

int main()
{

triangle  tri(4,2);


cout<<tri.area()<<endl;


return 0;
}

For some reason i am getting a zero in my exe when i should be getting a 4.

¿Fue útil?

Solución

You assigned value in wrong way:

update:

triangle::triangle(float base, float height)
{
  base=_base;
  height=_height;
}

to:

triangle::triangle(float base, float height)
{
   _base = base;
   _height = height;
}

Edit:

Also as @WhozCraig mentions, should use float for 1/2, or just

_base * _height / 2.0
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top