重载函数的问题 c++
原题是使用重载函数的方法定义两个函数,用来分别求出两个int型数的点间距离和浮点型数的点间距离。 #include<iostream.h> #include<math.h> int distan(int,int); float distan(float,float); void main() { int distance1; float distance2; distance1=distan(1,2); distance2=distan(1.35,2.78);//出错处 cout<<distance1<<distance2; } int distan(int x,int y) { int c=abs(x-y); return c; } float distan(float x,float y) { float c=abs(x-y);//错误处 return c; } d:\vc++ 6.0\myprojects\p1299\p7.cpp(10) : error C2668: 'distan' : ambiguous call to overloaded function d:\vc++ 6.0\myprojects\p1299\p7.cpp(20) : warning C4244: 'argument' : conversion from 'float' to 'int', possible loss of data d:\vc++ 6.0\myprojects\p1299\p7.cpp(20) : warning C4244: 'initializing' : conversion from 'int' to 'float', possible loss of data .请高手帮帮忙指点一下 小弟感激不尽
第一处错误的确如楼上所说,是因为数据类型不明确。由于1.35和2.78会被默认为double型而非float型,而你并没有提供含有double型输入参数的distan函数,因此就给编译器造成困扰,不明白究竟应该转换为int型还是float型。如果你在输入时写成1.35f和2.78f,则表示强制转换为float型,此时就不会报错了。 第20行报的是警告,是因为数据会被截断而导致计算误差,abs函数只支持int型,要计算float型或double型的绝对值则需用fabs函数。因此,这里你只需在abs前面加一个f即可。
1、第一个出错处:由于float参数后面没有加上f限定符,程序默认为double类型。所以重载函数报错。 2、第二个出错处:由于abs函数的参数是int型,float型向int型转换,又转换为float型,程序会警告损失数据精度。 正确程序如下: #include #include int distan(int,int); float distan(float,float); void main() { int distance1; float distance2; distance1=distan(1,2); distance2=distan(1.35f,2.78f);//改正出错处 couty) c =(x-y); else c =-(x-y); return c; }
在出错处,加上强制转换试试
答:#include #include using namespace std; //函数模板声明 template double dist(T t1,T t2...详情>>
问:挺简单的一C函数,不过我是初学者,暂时还不会写,请好心人多多帮忙!
答:int mystrlen(char *str) { int n = 0; while (*str) { n++; str++;} return n; } voi...详情>>