簡體   English   中英

為什么我從此循環中獲得此輸出?

[英]Why I am getting this output from this loop?

#include <iostream>
using namespace std;

我對cpp和編程非常陌生,我正在嘗試查找數字max的因數,為什么我的代碼輸出是這樣?

int max;
cout << "Enter a number you'd like to see the divisors of: " << endl;
cin >> max;

//I am trying to find all divisors for the number max
//I know this isn't the most efficienct way but I thought that it would work.
//Instead of 50, 25, 20, 10, 5 ,1 for output it looks like 50, 25, 25, 25 25, 5 

for (int t=1; t <= max; t++) {
  if (max % t == 0) {
    int m = max/t; 
  }
} 
cout << m << endl;

您的輸出放錯了位置。 移動cout << m << endl; 語句放入您的if語句塊中:

if (max % t == 0) { // start of a block
    int m = max / t;
    std::cout << m << '\n';
} // end of a block

確保使用大括號{}正確標記了語句塊 現在,對於給定的輸入50 ,輸出為:

50 25 10 5 2 1

關於Coliru的實時示例

using namespace std;

正如BO41所說,永遠不要使用命名空間,這有一些原因: 為什么“使用命名空間std”被認為是不好的做法?

除了應該使用名稱空間之外,還應該只寫正在使用的內容,例如:

using std::cout;
using std::endl;

現在回到問題:

for(int t=1; t <= max; t++){
    if(max % t == 0)
        int m = max/t; 
} cout << m << endl;

請注意,您是在if內定義m並在其外部使用它。 另外,如果不是那樣,您將只打印找到的最后一個除數。 您應該執行以下操作:

for(int t = 0; t <= max; t++){
    if(max % t == 0){
        int m = max/t
        cout << m << endl;
    }
}

在這里,您將打印最大除數的每個除數。 就我個人而言,即使該塊中只有一行,我也會始終為if語句打開一個塊,對我來說,它的組織性更高並且可以防止錯誤。

這是您的整個程序嗎? 變量

int m

超出范圍

cout << m << endl;

這使我相信您在程序中早先聲明了另一個名為“ m”的變量,該變量已被if塊中新聲明的int(也稱為“ m”)遮蓋。 如果是這種情況,則if塊外的先前聲明的變量“ m”將被打印到cout。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM