我正在尝试创建一个显示已从本地文件读取的温度的折线图。目前,除图形输出外,一切都按预期工作。
目前,我对负数的else
声明无效。此外,有些数字似乎显示,有些则没有。
最后,显示的数字没有显示正确的数字' *"。我知道我很接近但不能破解代码...
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std
int main()
{
//Variable declarations
int numberOfStars;
int printStars;
int temp;
int count = 0;
string lineBreak = " | ";
ifstream tempData;
tempData.open("tempData.txt");
cout << "Temperatures for 24 hours: " << endl;
cout << " -30 0 30 60 90 120" << endl;
printStars = 0;
while (count < 24) {
tempData >> temp;
if (temp >= 0) {
numberOfStars = temp / 3;
cout << setw(4) << temp << setw(10) << lineBreak;
while (printStars < numberOfStars){
cout << '*';
printStars++;
}
cout << endl << endl;
}
else {
numberOfStars = temp / 3;
while (numberOfStars > printStars) {
cout << '*';
printStars++;
}
cout << setw(4) << temp << setw(10)<< lineBreak << endl << endl;
}
count++;
}
//Closing program statements
system("pause");
return 0;
目前正在输出:
提前感谢您的帮助。
答案 0 :(得分:1)
哦,只需把你的printStars = 0;
放进去吧:)
如果你想要一个明星用于临时&lt; numberOfStars = temp / 3 + 1;
3。
编辑:您可以简化很多代码。您可以非常轻松地创建一个n字符时间的字符串。您的代码应如下所示:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
//Variable declarations
int numberOfStars;
int numberOfSpaces;
int temp;
int count = 0;
string lineBreak = " | ";
ifstream tempData;
tempData.open("data.txt");
cout << "Temperatures for 24 hours: " << endl;
cout << " -30 0 30 60 90 120" << endl;
while (count < 24) {
tempData >> temp;
numberOfStars = temp / 3 + 1;
if (temp >= 0) {
cout << setw(4) << temp << setw(10) << lineBreak;
cout << string(numberOfStars, '*');
}
else {
cout << setw(4) << temp;
numberOfSpaces = 7 + numberOfStars;
// Prevent any ugly shift
if (numberOfSpaces < 0)
{
numberOfSpaces = 0;
numberOfStars = -7;
}
cout << string(7 + numberOfStars, ' ');
cout << string(-numberOfStars, '*');
cout << lineBreak;
}
cout << endl << endl;
count++;
}
//Closing program statements
cin.get();
return 0;
}