我必須爲每個從輸入文件讀取的每個溫度每三度顯示一個星形的類進行編程。我認爲我沒有問題,代碼編譯。然而,當我真正運行它時,我遇到了一些問題:條形圖程序行爲奇怪
1)當我在代碼庫中不按Ctrl + F5運行它時,它立即退出,即使我'返回0;'最後。
2)控制檯只顯示大概一半數字的星星,其餘都是空白的。
3)雖然我已將它們全部設置爲我的循環中相同的寬度,但數字並不對齊。
這是我看到的時候我用ctrl + F5:http://imgur.com/w6jqPp5
這裏是我的代碼:
#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
//declare variables for input/loops
string graphLine = " | ";
int tempCount = 0;
int tempStars;
int tempValue;
int printedStars;
//Title
cout << "Welcome to the Hourly Temperature Bar-Graph Maker 1.0!" << endl;
//read input file, name it "tempData"
ifstream tempData;
tempData.open("temperatures.txt");
//display error if the input file read failed
if(!tempData) {
cout << "ERROR: The input file could not be read." << endl;
return 0;
}
cout << "Temperatures for 24 hours(each asterisk represents 3 degrees): " << endl;
//print the temperature range(horizontal label for graph)
cout << "-30 0 30 60 90 120" << endl;
//read a temperature, output the bar for each temperature
while (tempCount < 24) {
//read in temperature value
tempData >> tempValue;
//distinguish between negative and positive temperatures
if(tempValue >= 0) {
tempStars = tempValue/3;
cout << tempValue << setw(5) << graphLine;
//print the appropriate number of asterisks for the temperature
while (printedStars < tempStars) {
cout << '*';
printedStars++;
}
cout << endl;
}
//print the stars before the line
else {
tempStars = tempValue/3;
while (printedStars < tempStars) {
cout << '*';
printedStars++;
}
cout << tempValue << setw(5) << graphLine << endl;
}
tempCount++;
}
tempData.close();
return 0;
}
我認爲問題出在其他部分的寬度輸出,首先你有沒有初始化printedStars的價值。第二個if()條件是檢查tempValue> = 0;意味着它只會在tempValue爲負值時轉到其他部分,而在其他部分中,您正在檢查while(printedStars
Himanshu