在csharp中转换的问题 [英] Problem with Conversion in csharp

查看:63
本文介绍了在csharp中转换的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TimeSpan ts;
Single nomonths;
ts=startDate.Substract(endDate);
nomonths = Convert.toSingle(ts.days/30);  //ts.days=57



因此,在nomonths中必须获得1.9,但显示为1

请帮助我.



So in nomonths has to get 1.9 but it is showing 1

Please help me.

推荐答案

否!

No!

double nomonths = Convert.TotalDays / 30d;



正确阅读System.TimeSpan帮助( http://msdn.microsoft.com/en-us/library /system.timespan.aspx [ ^ ]).不以总计"为前缀的属性返回整数值,但您需要浮点数.

您的问题是:将整数除以整数就可以将整数值转换为单值.甚至在调用Convert函数之前就切掉了小数部分(这完全是多余的).

—SA



Read System.TimeSpan help properly (http://msdn.microsoft.com/en-us/library/system.timespan.aspx[^]). Properties not prefixed with "Total" return integer value, but you need floating point.

Your problem was: division integer by integer gives you integer value converted to single. The fractional part was cut even before calling Convert function (which is totally redundant).

—SA


这是一个非常基本的编程错误.假设您是初学者,我已经选择了特殊的应用名称
就我的例子而言...

阅读有关隐式和显式强制转换,基本数据类型和精度的信息.这些是您在每种编程语言中都会遇到的主题-您必须了解它!

This is a very basic programming error. Assuming you are a beginner I''ve choosen a special app name
for my example...

Read about implicit and explicit casting, basic datatypes and precision. These are topics you come across in every programming language - you have to know it!

using System;
namespace ReadChapterOneOfAnyNETBook
{
    class Program
    {
        static void Main(string[] args)
        {            
            DateTime startDate = DateTime.Now.AddDays(-57d);
            DateTime endDate = DateTime.Now;
            TimeSpan ts = endDate - startDate;
            float numberOfMonths = (float) ts.TotalDays / 30f;
            Console.WriteLine(numberOfMonths);
            Console.ReadKey();
        }
    }
}


这篇关于在csharp中转换的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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