我尝试使用以下代码通过while循环求和数组的元素
Here is the errors.php file
<?php if(count($errors) > 0): ?>
<div class="error">
<?php foreach ($errors as $error): ?>
<p><?php echo $error; ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
但是它会引发错误
Here is the form section that I created in HTML
<!-- Login page container -->
<form method="post" action="register.php">
<!-- display validation errors here -->
<?php include('errors.php'); ?>
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstname"><b>First Name</b></label>
<input type="text" placeholder="Enter first name" name="firstname" required>
<label for="lastname"><b>Last Name</b></label>
<input type="text" placeholder="Enter last name" name="lastname" required>
<label for="streetaddress"><b>Street Address</b></label>
<input type="text" placeholder="Enter Street Address" name="streetaddress" required>
<label for="city"><b>City</b></label>
<input type="text" placeholder="City" name="city" required>
<label for="state"><b>State</b></label>
<input type="text" placeholder="Enter State" name="state" required>
<label for="zipcode"><b>Zip Code</b></label>
<input type="text" placeholder="Enter Zip Code" name="zipcode" required>
<label for="phonenumber"><b>Phone Number</b></label>
<input type="text" placeholder="Enter Phone Number" name="phonenumber" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" value="<?php echo $email; ?>">
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" value="<?php echo $password; ?>">
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
<button type="submit" name= "register" class="registerbtn">Register</button>
</div>
<div class="container signin">
<p>Already have an account? <a href="internallogin.php">Sign in</a>.</p>
</div>
</form>
我也尝试使用return def sum(input: Array[Int]): Int = {
var i=0;
while(i<input.length) {
sum=i+input(i);
i=i+1;
}
sum
}
,但出现了另一个错误
<console>:17: error: reassignment to val
sum= (i+input(i))
^
<console>:21: error: missing argument list for method
sum Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `sum _` or `sum(_)` instead of `sum`.
如何使用while循环求和数组的元素?
答案 0 :(得分:3)
我认为您要这样做的是
def sum(input:Array[Int]):Int = {
var i, res = 0;
while(i < input.length) {
res = res + input(i); // and not res=i+input(i);
i = i + 1;
}
res
}
这基本上是使用累加器变量res
来累加Array
的不同值,而不能使用sum
这是它的方法名称。
答案 1 :(得分:0)
def sum(input: Array[Int]): Int = input.sum
如果某个东西有内置的例程,那么最好使用它。如果这只是编程工作,那么您不应该使用var
和while
,而是使用foldLeft
或递归例程是更好的解决方案。
答案 2 :(得分:0)
在不使用while循环或vars的情况下,汇总列表的方法很少。
val l = List(1,2,3,4,5)
l.reduce((a,b) => a + b)
l.foldLeft(0)((a,b) => a + b)
def sum(l: List[Int]): Int = l match {
case Nil => 0
case head :: tail => head + sum(tail)
}
sum(l)
它们应该总计为15。