1. 请用c语言编写程序,求和:S = 1-(1/2)+(1/3)-(1/4)+…+(1/n),其中n=10
#include"stdio.h"
int main(){
int i = 1;
int tag = 1; //表示符号
double sum = 0;
while(i<=10){
sum += tag*(1.0/i);
i++;
tag *= -1;
}
printf("%f\n",sum);
return 0;
}
2. 请用C语言编写一个函数fun(char *s),该函数的功能是:把字符串中的内容逆置。
例如:字符串中原有的字符串有"abcdefg",则调用该函数后,串的内容改为"gfedcba"。
#include"stdio.h"
#include"stdlib.h"
char* fun(char *s){
int length = 0;
char *c = s;
while(*c != '\0'){
length++;
c++;
}
char *new_s = (char *)malloc(sizeof(char)*length);
int i=0;
while(i<length){
new_s[i] = s[length-i-1];
i++;
}
return new_s;
}
int main(){
char s[]="abcdefg";
//char s[20];
//gets(s);
char *new_s;
new_s=fun(s);
puts(new_s);
return 0;
}
3. 编写程序从基类派生圆柱,设计成员函数输出它们的面积和体积。
基类定义如下:
class Basic//基类
{
protected:
double r;
public:
Basic() { r = 0; }
Basic(double a){ r = a;}
};
#include <iostream>
#define pi 3.1415926
using namespace std;
class Basic{
protected:
double r;
public:
Basic(){
r = 0;
}
Basic(double a){
r = a;
}
};
class cylinder:public Basic {//圆柱
private:
double h;
public:
cylinder(double b,double a){
r = a;
h = b;
}
double get_area(){ //面积
return pi*r*r;
}
double get_volume(){ //体积
return get_area()*h;
}
};
int main()
{
cylinder c(5,2);
cout<<c.get_area()<<endl;
cout<<c.get_volume()<<endl;
return 0;
}