C++ C++;线图表现得很古怪
我试图创建一个折线图,显示从本地文件读取的温度。目前,除图形输出外,其他一切都正常工作 现在,我对负数的C++ C++;线图表现得很古怪,c++,visual-c++,C++,Visual C++,我试图创建一个折线图,显示从本地文件读取的温度。目前,除图形输出外,其他一切都正常工作 现在,我对负数的else语句工作不正常。此外,有些数字似乎显示出来,有些则没有 最后,显示的数字没有显示“*”的正确数字。我知道我很接近,但无法破解代码 #include <iostream> #include <string> #include <iomanip> #include <fstream> using namespace std int mai
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;
#包括
#包括
#包括
#包括
使用名称空间std
int main()
{
//变量声明
国际数星;
国际印刷之星;
内部温度;
整数计数=0;
字符串lineBreak=“|””;
ifstream-tempData;
tempData.open(“tempData.txt”);
哦,把你的printStars=0;
放在while:)
如果你想让temp<3有一颗星,那么就做numberOfStars=temp/3+1;
编辑:您可以大大简化代码。您可以非常轻松地创建一个包含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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
//变量声明
国际数星;
整数空间;
内部温度;
整数计数=0;
字符串lineBreak=“|””;
ifstream-tempData;
tempData.open(“data.txt”);
你难道不明白temp
必须是负数,才能执行else
分支吗?因为这就是if
语句所说的。所以,如果temp
是负数,突击测验:你认为temp/3
是正数还是负数?你知道printStars
必须是正数,那么你认为while(numberOfStars>printStars)
为真的几率有多大呢?是的,我知道要执行else语句,temp必须为负。我想我只是不理解逻辑。这就是我所理解的情况。-21/3=-7。所以,while(-7>0)打印一个“”。因此,由于它的数量较少,所以不会发生任何事情。但是,当我将while语句切换到while(numberOfStars