C语言中最简单的操作不起作用 [英] Simpliest operation in C not working

查看:96
本文介绍了C语言中最简单的操作不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
可能的分数损失
C中整数除法的行为是什么?

Possible Duplicates:
Possible Loss of Fraction
What is the behavior of integer division in C?

我是C语言的新手,遇到了一些麻烦.以下代码:

I'm new to C and I have some troubles. The following code:

int nr = 3;
float fl = nr/10;
printf("%4.1f\n", fl);

按我的预期打印0.0,但不打印0.3.有什么问题吗?

Prints 0.0 but not 0.3 as I expected. What's the problem?

推荐答案

nr是一个整数,因此您仍在进行整数除法,但将其分配给浮点数.将nr强制转换为浮点数:

nr is an int, so you're still doing integer division, but assigning it to a float. Cast nr to a float instead:

float fl = (float) nr / 10;
// or divide by a float
float fl = nr / 10.0f;

这篇关于C语言中最简单的操作不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆