返回奇数的简单模板?
在阅读之前编辑:抱歉..我没有添加换行符,所以看起来很混乱,我无法删除问题,因为我还没有注册,抱歉浪费了你们的时间。
我只是第一次使用模板(用于查找两个数字的最小值)而不是宏,我喜欢它!但是当我尝试修改并制作自己的模板时,它完全失败了。这是我的代码:
#include <stdio.h>
template <class T> T min(T a, T b) {
return a < b ? a : b;
};
//My attempt now.. because add could be int, float, etc; I wanted a template.
template <class T> T add(T a, T b) {
return a + b;
};
int main(){
printf("%f\n", min(1.3, 2.2)); //(Does not appear in console?)
printf("%d", add(1, 10)); //1.300000 (how is an int show as float? lol)
printf("%f", add(5.1, 7.34)); //1112.440000
return 0;
}
现在奇怪的结果在注释中。Min 工作正常,但是当我将其从比较更改为“a + b”时,它停止了分钟的工作,并给我奇怪的浮点值?!
我使用它的方式错误吗? ,应该是别的东西吗?这意味着什么?我了解基础知识,所以简单的解释就可以了。谢谢!
EDIT BEFORE YOU READ: Sorry.. I didn't add newline so it appeared jumbled, I can't delete the question because I'm not registered yet, sorry for wasting your time guys.
I just used a template for the first time (for finding MIN of two numbers) instead of a macro, and I liked it! But when I tried to modify and make my own template it failed completely.. Here is my code:
#include <stdio.h>
template <class T> T min(T a, T b) {
return a < b ? a : b;
};
//My attempt now.. because add could be int, float, etc; I wanted a template.
template <class T> T add(T a, T b) {
return a + b;
};
int main(){
printf("%f\n", min(1.3, 2.2)); //(Does not appear in console?)
printf("%d", add(1, 10)); //1.300000 (how is an int show as float? lol)
printf("%f", add(5.1, 7.34)); //1112.440000
return 0;
}
Now the strange results are in the comments.. Min works fine, but when I change it from comparison to "a + b" it stops min from working, and hands me weird float values?!
Am I using it the wrong way? , is it supposed to be something else? what does that mean? I understand the basics so a simple explaination would be alright.Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试在其他行之后也添加换行符。
发生的情况是这样的:
min(1.3, 2.2)
,即1.300000
add(1, 10)
,这是11
add(5.1, 7.34)
这是12.440000
由于步骤 3 和 4 之间没有换行符,所以它打印数字直接在彼此之后,使其看起来像这样:
1112.440000
。Try adding linebreaks after the other lines too.
What happens is this:
min(1.3, 2.2)
which is1.300000
add(1, 10)
, which is11
add(5.1, 7.34)
which is12.440000
Since there is no linebreak between step 3 and 4, it prints the number directly after each other, making it look like this:
1112.440000
.一旦您开始替换 C 习惯,请查看流:
Once you're at replacing C habits, check out streams: