乘以下一个数字

时间:2015-04-27 11:45:33

标签: c++ xcode

我尝试编写一个程序,将输入数字乘以2,然后将该答案乘以2循环,但是我无法让我的程序乘以第二个数字,这里&#我的代码。

int main() {

    int number;

    cout << "Enter a number: ";
    cin >> number;

    while (true) {
        int multiply = number * 2;
        cout << "Answer: " << multiply << endl;
    }  
} 

如何使此程序乘以之前相乘的数字? 提前致谢!

4 个答案:

答案 0 :(得分:6)

只需重复使用相同的变量:

while (true) {
    number = number * 2; // The same !
    cout << "Answer: " << number << endl;
}

但是不要期望程序正常运行直到时间结束:int变量的最大值为(2 ^ 31 - 1),因此在最多30次迭代时它可以正常运行。

答案 1 :(得分:3)

您将一次又一次地“存储”相同的值。

为了达到目标,您需要将结果存储在“乘法”中,然后将* 2存储在此变量中。 像这样:

int multiply = number * 2;

while (true) {
    cout << "Answer: " << multiply << endl;
    multiply = multiply * 2;

}  

编辑: 更优雅的方法是使用递归函数。 您可以找到一个有用的示例here

答案 2 :(得分:1)

使用此,

   int multiply = number;

    while (true) {

        multiply = multiply *2;
        cout << "Answer: " << multi << endl;
    }

答案 3 :(得分:1)

public class MapsActivity extends FragmentActivity implements LocationListener { private GoogleMap mMap; // Might be null if Google Play services APK is not available. int f=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } private void setUpMap() { mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker")); } @Override public void onLocationChanged(Location location) { Log.d("DanT", "location changed"); //if(f==1) // { location.getLatitude(); location.getLongitude(); // f=2; //} String Text = "My current location is: " + "Latitud = " + location.getLatitude() + "Longitud = " + location.getLongitude(); TextView txtgps = (TextView) findViewById(R.id.loc_textView); txtgps.setText(Text); Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT).show(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } } 每次迭代都具有相同的值。您希望每次number乘以2,而不是multiply

第一次迭代是特殊情况,因此您必须弄清楚如何初始化number以使其有效。