VB.NET concatenation error

こ雲淡風輕ζ 提交于 2019-12-12 06:56:49

问题


I have this line of code which I want to concatenate -or at least solve the loop problem...

test = 1 - ("0." & thisnumber(0) & thisnumber(1) & thisnumber(2))

I want this to have a loop in it...

-Increasing thisnumber()

Until it gets to about 500,

Can some implement a loop into this?

Or suggest a way...

Thanks a lot..

James :)

EDIT:

So if I had values thisnumber(0) = 1, thisnumber(1) = 5, thisnumber(2) = 0, thisnumber(3) = 7... It would do 1 - 0.1507... (But I want a loop so it does all 500 without me typing them all out) -I'm wanting 1,000,000 so it would be a huge problem.


回答1:


Something like this, maybe... (Excuse my VB syntax, it's been a while)

dim num as double = 0.0

for i as integer = 0 to 500
    num += thisnumber(i) / (10 ^ (i + 1))
next 

test = 1 - num

However... this will overflow way before you get to 500 digits, and I still have to wonder why your input is in this format in the first place...

EDIT: based on the OP's comments, here's a version minus overflow...

dim num as double = 0.0
dim factor as double = 1.0;

for i as integer = 0 to 500
    factor /= 10
    num += thisnumber(i) * factor
next 

test = 1 - num

This version won't overflow, but you'll run into decimal precision issues along the way. If, as the OP suggests, this is about finding Pi to high accuracy, there are probably better ways - but without knowing the actual problem, I'm not sure it's worth going into detail.




回答2:


The string concatenation is super confusing here. I think you're actually trying to do arithmetic, yes? You want a loop in which you're incrementing both the integer you pass to thisnumber() and the power of ten you're dividing by. So you have 1 - thisnumber(0)/10 - thisnumber(1)/100 / thisnumber(2)/1000 and so on. You should be able to do that with a loop once you stop thinking about building a string.

Update: what type are you planning to use for test? Do you understand how many decimal places of precision it can hold if it's a number? If it's a string, what are you going to do with it once you have it?




回答3:


Use a DO ... WHILE loop




回答4:


Dim d As Integer
Dim val As String
val = "0."
For d = 0 To 500
    val = val & d
Next d
test = 1 - Convert.ToDouble(val)


来源:https://stackoverflow.com/questions/3086430/vb-net-concatenation-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!