【问题标题】:iPhone SDK math - pythagorean theorem problem!iPhone SDK 数学 - 勾股定理问题!
【发布时间】:2010-05-12 20:58:03
【问题描述】:

作为一种练习,我正在开发一个应用程序来解决著名的中学勾股定理,a squared + b squared = c squared。不幸的是,在我看来,即将到来的答案与实际答案无关。这是“解决”操作期间使用的代码。

- (IBAction)solve {
 int legoneint;
 int legtwoint;
 int hypotenuseint;

 int lonesq = legoneint * legoneint;
 int ltwosq = legtwoint * legtwoint;
 int hyposq = hypotenuseint * hypotenuseint;

 hyposq = lonesq + ltwosq;

 if ([legone.text isEqual:@""]) {
  legtwoint = [legtwo.text intValue];
  hypotenuseint = [hypotenuse.text intValue];

  answer.text = [NSString stringWithFormat:@"%d", legoneint];
  self.view.backgroundColor = [UIColor blackColor];
 }
 if ([legtwo.text isEqual:@""]) {
  legoneint = [legone.text intValue];
  hypotenuseint = [hypotenuse.text intValue];

  answer.text = [NSString stringWithFormat:@"%d", legtwoint];
  self.view.backgroundColor = [UIColor blackColor];
 }
 if ([hypotenuse.text isEqual:@""]) {
  legoneint = [legone.text intValue];
  legtwoint = [legtwo.text intValue];

  answer.text = [NSString stringWithFormat:@"%d", hypotenuseint];
  self.view.backgroundColor = [UIColor blackColor];
 }
}

顺便说一下,legone, legtwo, and hypotenuse 都表示对应于直角三角形每个数学部分的UITextFieldAnswerUILabel,它告诉你答案,你猜对了。有没有人看到程序中的任何缺陷?提前致谢!

【问题讨论】:

    标签: iphone math pythagorean


    【解决方案1】:

    没有仔细检查程序但是在第一行已经有一个大问题:

    int lonesq = legoneint * legoneint;
    int ltwosq = legtwoint * legtwoint;
    int hyposq = hypotenuseint * hypotenuseint;
    

    这个变量是使用仍然没有分配的变量定义的。您需要设置从文本字段中获取的变量的值,然后进行数学运算。 C是顺序语言,一切都是从上到下执行的,不能说“a = bc”,在程序的任何地方a都会是bc。

    【讨论】:

    • 这是一个很好的例子,说明在许多过程编程语言中使用“=”如何使人们感到困惑。这不是平等,这是分配。所以语言设计者,要么使用不同的符号(比如 ':='),要么让它实际上意味着相等(比如在 Haskell 中)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2015-07-23
    • 2013-02-13
    • 2021-09-20
    • 1970-01-01
    • 2010-10-20
    • 2019-10-08
    相关资源
    最近更新 更多