从Excel转换方程到C#

我试图将Excel电子表格转换为用C#编写的小程序。

我在excel上的等式是:

if(S6>=3.55;1;if(S6>2.25;0.8;if(S6>1.61;0.65;0.5))) 

其中S6是我检查的值被写入的单元格。

我尝试了以下内容:

  if (width>=3.55) { double radius = 1.0; else if (width>2.25 ) { double radius = 0.8; } else if (width>1.6 ) { double radius = 0.65; } else { double radius = 0.5; } } 

但它不起作用,所以我错过了,我应该如何声明与variables宽度相关的variables半径? 在C#上的消息说,我不能在当前范围声明variables“半径”,我应该在循环之前声明variables? MSDN帮助文件只在if语句中使用一个带有return语句的固定值,这意味着我不能在if {}循环中拥有variables依赖关系吗?还有,还有其他更有效的方法来做这种条件逻辑吗?

一个if块不包含else / else if语句。 您需要先closures原来的if语句。 另外,在每个范围内声明一个局部variables并且不使用它是没有意义的。 您可能想要在任何if / else块的范围之外声明radius

 double radius; if (width>=3.55) { radius = 1.0; } else if (width>2.25 ) { radius = 0.8; } else if (width>1.6 ) { radius = 0.65; } else { radius = 0.5; } 

if语句之上声明radius 修复你的大括号。 正确alignment一切。

 double radius = 0; if (width >= 3.55) { radius = 1.0; } else if (width > 2.25 ) { radius = 0.8; } else if (width > 1.6 ) { radius = 0.65; } else { radius = 0.5; } 

if语句中声明radiusvariables会导致variables在离开ifelse语句时超出范围(消失)。