我想写一个面向对象的程序。我不太了解它。它在我看来它有点类似于Fortran中的子程序。我在下面创建了一个示例程序。你可以帮我把它翻译成C ++代码吗? c在Fortran中编程以计算矩形的面积和周长
implicit double precision(a-h,o-z), integer(i-n)
dimension a(10),p(10)
xl = 0.0
xb = 0.0
do 10 ix = 1,10
call area(xl,xb,a)
call perimeter(xl,xb,p)
write(*,*) ix,a(ix),p(ix)
xl = xl + 1.0
xb = xb + 1.0
10 continue
end
subroutine area(xx,yy,ara)
implicit double precision (a-h,o-z),integer(i-n)
dimension ara(10)
do 40 j = 1,10
ara(j) = xl*xb
40 continue
return
end
subroutine perimeter(xl,xb,per)
implicit double precision (a-h,o-z),integer(i-n)
dimension per(10)
do 50 i=1,10
per(i) = 2*(xl+xb)
50 continue
return
end
谢谢。
答案 0 :(得分:1)
我不是Fortran,但这看起来就像你所得到的(如果不是你想要的,请澄清):
#include<vector> // allows you to use the C++ STL std::vector (think of it as a better array)
// calculates the area of a rectangle
double rectangle_area( const double height, const double width )
{
return height*width;
}
// calculates the perimeter of a rectangle
double rectangle_perimeter( const double height, const double width )
{
return 2*height+2*width;
int main()
{
const int N = 10; // defined a constant integer
std::vector<double> area( N ); // creates a vector of double precision floats of size N
std::vector<double> perimeter( N ); // idem
double width = 0.;
double height = 0.;
for( int i = 0; i < 10; ++i ) // loop over i from 1 to 10, incrementing (++i) after each iteration
{
area[i] = rectangle_area( width, height );
perimeter[i] = rectangle_perimeter( with, height );
width += 1.; // same thing as 'width = width + 1' or width++;
height += 1.; // idem
}
return 0;
}
请注意,这不会向屏幕输出任何内容。要在C ++中输出数字或字符串,您需要#include <iostream>
并使用以下语法:
std::cout << variable_you_want_to_output << std::endl;
std::endl
插入换行符并刷新输出流。