我想要一個傳遞一個整數的函數,並且如果該整數超過某個值(在我當前的情況下爲1000),我想對它執行一些除法我最終可以返回原始整數的縮寫。將字符串格式化爲1小數位,無需向上/向下舍入
例如:
1000 = 1
1001 = 1
1099 = 1
1100 = 1.1
1199 = 1.1
1200 = 1.2
10000 = 10
10099 = 10
10100 = 10.1
這是分裂和事情已經引起了我的問題四捨五入的一面。
什麼是最適合上述結果的方法?
我想要一個傳遞一個整數的函數,並且如果該整數超過某個值(在我當前的情況下爲1000),我想對它執行一些除法我最終可以返回原始整數的縮寫。將字符串格式化爲1小數位,無需向上/向下舍入
例如:
1000 = 1
1001 = 1
1099 = 1
1100 = 1.1
1199 = 1.1
1200 = 1.2
10000 = 10
10099 = 10
10100 = 10.1
這是分裂和事情已經引起了我的問題四捨五入的一面。
什麼是最適合上述結果的方法?
如何:
int dividedBy100 = x/100; // Deliberately an integer division
decimal dividedBy1000 = dividedBy100/10m; // Decimal division
string result = dividedBy1000.ToString();
我會通過10
縮寫根據定義舍入。
如果您正在尋找更高的精度,爲什麼不使用Double而不是Integer?
如果t爲原來的號碼,然後
int a=t/100
float b=a/10
乙方應包含你的答案
更多的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
string s;
s = Console.ReadLine();
int a = Convert.ToInt32(s);
a = a/100;
float b = a/(float)10.0;
Console.WriteLine(b);
}
}
}
}
這裏有一個建議
double function(int number)
{
if (number >= 1000)
{
return (((double)number)/1000);
}
}
試
int MyNumber = 10100;
string MyString = ((int) MyNumber/1000).ToString() + ((MyNumber % 1000) > 99 ? "." + (((int)(MyNumber/100)) % 10).ToString() : "");
當OP說他想要'10'(無小數點)時,這會在'10000'打印'10.0'。 –
沒有意識到...更正... – Yahia
你的例子似乎暗示你只想要精確小數點後一位,所以怎麼是這樣的:
第一部分將截斷小於100的任何尾數(相當於100個基底的函數), ñ鑄造加倍和10除以將給你你想要的精度的單一小數位。
使用decimal
而不是在這裏float
或double
,因爲你根本想小數師建議你應該使用模塊化(餘)數學要做到這一點。您不需要涉及FPU(浮點單元)。
static string RoundAndToString(int value, int denominator)
{
var remainder = value % denominator;
value = (value - remainder)/denominator;
if (remainder == 0)
return value.ToString();
remainder = (remainder * 10)/denominator;
return string.Format("{0}{1}{2}", value, CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, remainder);
}
既然你只是想截斷的數量,是有意義的是最後兩個字符轉換爲字符串,刪除從字符串,然後除以10,以獲得相應的編號。
這裏是Ruby中的算法。(我沒有C#方便)
a = 1000 #sample number
-> 1000
b = a.to_s[0..-3] #a converted to a string, then taking all characters except the last two.
-> "10"
c = b.to_i/10.0 # converts to float in correct power
-> 1.0
然後,您可以顯示任何格式你想使用的sprintf(或使用FormatNumber C#的當量) 「C」。
你在找什麼是「截斷」,這是一種稱爲「向0取整」的舍入形式。 – Gabe