【发布时间】:2011-09-09 07:51:45
【问题描述】:
我正在编写一个程序来计算用户输入的简单数字。 2、4、7、10、12 等等。
我需要程序以某种方式存储这些输入(来自不同的文本字段)。在内部方程式中使用它们,然后最终将它们展示给用户。
我该怎么做?请注意,我是编程新手。
我知道如何定义 textFields,计算 IBAction,并且我尝试创建一个 -(void)calculate,它有效,但仅适用于 1 个输入。当我执行以下代码时,输入来自 6 个文本字段而不是 3 个(在第一行 (resultOne) 中使用),它给了我错误的数字。但我仍然需要更好的方法来做到这一点。
-(void) calculate{
weightOne = [v1Text.text floatValue]/2;
weightTwo = [v2Text.text floatValue]/2;
resultOne = [m1Text.text floatValue] * weightOne + [s1Text.text floatValue] * weightOne;
resultTwo = [m2Text.text floatValue] * weightTwo + [s2Text.text floatValue] * weightTwo;
_resultTotal = (resultOne + resultTwo) / (weightOne + weightTwo);
NSString *resultString = [[NSString alloc]
initWithFormat: @"%.2f", resultOne];
resultLabel.text = resultString;
[resultString release];
}
我知道上面的代码输出了resultOne,但这只是为了我自己的测试,要知道等式是否有效。但我真的很想重新开始,因为我不相信上面的代码适合我需要它做的事情。
请记住,我是一个初学者,并解释一下,而不仅仅是向我展示一些代码。
我期待您能给我任何帮助。
编辑! - 以下是新代码
-(IBAction) calculate:(id)sender {
weightOne = 1;
weightTwo = 0.75;
weightThree = 0.50;
mOne = [m1Text.text floatValue];
mTwo = [m2Text.text floatValue];
sOne = [s1Text.text floatValue];
sTwo = [s2Text.text floatValue];
resultOne = (mOne*weightOne) + (sOne*weightOne);
resultTwo = (mTwo*weightTwo) + (sTwo*weightTwo);
_resultTotal = (resultOne + resultTwo) / (weightOne*2 + weightTwo*2);
NSString *resultString = [[NSString alloc]
initWithFormat: @"Gennemsnit %.2f", _resultTotal];
resultLabel.text = resultString;
}
我决定更改我的代码,以便轻松计算输入。现在我还有一个问题。
是否可以以某种方式保存这个方程式,这样我就可以根据需要多次重复使用它,而不必一次又一次地键入代码。
【问题讨论】:
-
这段代码看起来不错,我不知道你为什么不满意!当您有更多输入时会出现什么问题?
-
问题是我不知道如何存储用户输入以供以后使用。用户需要在 15x2 的文本字段中输入多达 30 个等级,具体取决于他们参加的课程数量。然后,我需要以一种简单的方式计算成绩,并最终将其显示给用户。我不确定如何使用我目前拥有的代码来做到这一点。
标签: iphone objective-c textfield