Foreach-怎么了?

时间:2019-05-25 16:19:18

标签: java

下面的两个示例都应该对数组元素求和,但是这没有发生。在第一个中,我得到了总和,但是在第二个中,我得到了数组中的值。怎么了?

  • Java-

第一个:

< double [] arr = {1.0,2.0,3.0,4.0,5.0};
    double sum = 0.0;

    for (int i = 0 ; i<arr.length; i++) {
            sum += arr[i];              

        System.out.println ("arr sum is :" + sum); }
>

第二个:

<  double [] arr = {1.0,2.0,3.0,4.0,5.0};
    double sum = 0.0;

    for (double d : arr) {
    sum += d;

    System.out.println (d);  }

>

第一个结果是:

arr sum is :1.0
arr sum is :3.0
arr sum is :6.0
arr sum is :10.0
arr sum is :15.0

但第二个返回:

1.0
2.0
3.0
4.0
5.0

2 个答案:

答案 0 :(得分:0)

在第二个示例中,您正在打印d,而应该打印sum变量:

double [] arr = {1.0,2.0,3.0,4.0,5.0};
double sum = 0.0;

for (double d : arr) {
    sum += d;
    System.out.println(sum);  // fixed
}

答案 1 :(得分:-2)

对于第二个,您正在打印相加而不是和的数字。如果您将代码更改为此,它将起作用:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
<script>
  var map, infoWindow;
  var marker;

  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {
        lat: 28.961856892883443,
        lng: 50.83683013916016
      },
      zoom: 15,
      gestureHandling: 'greedy',
    });
    infoWindow = new google.maps.InfoWindow;

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var location = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        marker = new google.maps.Marker({
          position: location,
          map: map
        });
        infoWindow.open(map);
        map.setCenter(location);


      }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
      });
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  }

  function handleLocationError(browserHasGeolocation, infoWindow, location) {
    alert("Error");
    infoWindow.open(map);
  }

  // New marker by click on map
  $(document).ready(function() {
    function placeMarker(location) {
      if (marker) {
        marker.setPosition(location);
      } else {
        marker = new google.maps.Marker({
          position: location,
          map: map
        });
      }
    }

    google.maps.event.addListener(map, 'click', function(event) {
      placeMarker(event.latLng);
    });
  });

</script>