[快速结贴]小问题一个,

kkun_3yue3 2008-07-10 04:57:57
说,有N个变量

string a = "0";
string b = "5.5";
string c = "";
string d = "50";
....略


求,不为空的变量,转换为INT后的平均数

如上例应该是
(0+5.5+50)/3
而不是除以4



...全文
149 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
mytvgames 2008-07-10
  • 打赏
  • 举报
回复
string[] strArray = { "5","5.5",""};
int numCount = 0;
int sum = 0;
foreach (string s in strArray) {
try {
double dtemp = double.Parse(s);
int intValue = (int)dtemp;
numCount++;
sum += intValue;
} catch {

}
}
double avg = sum / numCount;
syl2000 2008-07-10
  • 打赏
  • 举报
回复
假设变量以string[]形式存放

int myAvg(string[] pstr)
{
int iCnt = 0;
int iVal = 0;
foreach(string ss in pstr)
{
if(ss.Length > 0)
{
iCnt++;
iVal = iVal + Convert.ToInt32(ss);
}
}
int iRet = iVal/iCnt;
return iRet;
}
beancurd005 2008-07-10
  • 打赏
  • 举报
回复
string a = "0";
string b = "5.5";
string c = "";
string d = "50";

List<string> list=new List<string>();
list.Add(a);
list.Add(b);
list.Add(c);
list.Add(d);

int count=0;
int total=0;
foreach(string s in list)
{
if(!String.IsNullOrEmpty(s))
{
total += Int32.Parse(s);
count ++;
}
}
if(count !=0)
{
double average = double(total/count);
}
halk 2008-07-10
  • 打赏
  • 举报
回复

int 除数 = 0;
double 被除数 = 0;
double 数;

if(double.TryParse(a, out 数)
{
除数 += 1;
被除数 += 数;
}
if(double.TryParse(b, out 数)
{
除数 += 1;
被除数 += 数;
}
if(double.TryParse(c, out 数)
{
除数 += 1;
被除数 += 数;
}

……

double 商 = 被除数 / (double)除数;
int 整数的商 = (int)商;

jeason_jun 2008-07-10
  • 打赏
  • 举报
回复
若这些变量是个数组a

int n=0;
int sum=0;
double avg;
for(int i= 0;i<a.lenth;i++)
{
try
{
sum+=convert.toint32(a[i]);
n++;
}
catch{}
}

avg=sum/n;
Macosx 2008-07-10
  • 打赏
  • 举报
回复
string[] rawValues = { "0", "5.5", "", "50" };
double val=0;
var ave = from numString in rawValues
where Double.TryParse(numString, out val)
select val;

Console.WriteLine(ave.Average());
我姓区不姓区 2008-07-10
  • 打赏
  • 举报
回复
能不能把这些string放到一个List<string>中
nattystyle 2008-07-10
  • 打赏
  • 举报
回复
很简单,判断变量的length,代码略
nattystyle 2008-07-10
  • 打赏
  • 举报
回复
求,不为空的变量,转换为INT后的平均数

如上例应该是
(0+5.5+50)/3

string b = "5.5";

转换成int后等于5.5???

楼主,弓虽!

110,024

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧