gpt4 book ai didi

c++ - 从输入中获取数字和单位作为 double 和字符串——编程 : Principles and Practices Using C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:03:50 25 4
gpt4 key购买 nike

为了自己的利益,我一直在阅读 Bjarne Stroustrup 的编程:使用 C++ 的原则和实践。这不是家庭作业,也不适合学校。

我对第 4 章中的这个练习束手无策。我应该从输入中获取一个数字和一个单位,在 while 循环中将数字存储为 double ,将单位存储为字符串,然后跟踪迄今为止看到的最大和最小数字。它非常适用于像“m”或“g”这样的一个字符单位,但是当我输入一个双字符单位如“cm”或“ft”时,循环结束并且程序终止。下面是我的代码:

#include <iostream>

using namespace std;

int main()
{
double temp = 0;
string unit = " ";
double largest = 0;
double smallest = 0;

while (cin >> temp >> unit)
{
if (largest == 0 && smallest == 0)
{
largest = temp;
smallest = temp;
cout << "That's the largest number seen so far.\n";
cout << "That's the smallest number seen so far.\n";
}
else if (temp >= largest)
{
largest = temp;
cout << "That's the largest number seen so far.\n";
}
else if (temp <= smallest)
{
smallest = temp;
cout << "That's the smallest number seen so far.\n";
}
else
{
cout << temp << '\n';
}

}
return 0;
}

我非常感谢任何帮助解决这个问题的人。这让我发疯。

最佳答案

我需要 #include <string>在它甚至可以编译之前,我添加了额外的“printf()”stmts 用于调试。

但是您的代码应该可以工作:一个字符或多个字符。

这是我的(修改后的)代码:

#include <iostream>
#include <string>

using namespace std;

int main()
{
double temp = 0;
string unit = " ";
double largest = 0;
double smallest = 0;

while (cin >> temp >> unit)
{
cout << "NEXT: temp=" << temp << ", unit=" << unit << "\n";
if (largest == 0 && smallest == 0)
{
largest = temp;
smallest = temp;
cout << "That's the largest number seen so far.\n";
cout << "That's the smallest number seen so far.\n";
}
else if (temp >= largest)
{
largest = temp;
cout << "That's the largest number seen so far.\n";
}
else if (temp <= smallest)
{
smallest = temp;
cout << "That's the smallest number seen so far.\n";
}
else
{
cout << temp << '\n';
}

}
cout << "DONE: temp=" << temp << ", unit=" << unit << ", smallest=" << smallest << ", largest=" << largest << "\n";
return 0;
}

这是示例输出:

12 cm
NEXT: temp=12, unit=cm
That's the largest number seen so far.
That's the smallest number seen so far.
6 "
NEXT: temp=6, unit="
That's the smallest number seen so far.
18 feet
NEXT: temp=18, unit=feet
That's the largest number seen so far.
^D
DONE: temp=18, unit=feet, smallest=6, largest=18

关于c++ - 从输入中获取数字和单位作为 double 和字符串——编程 : Principles and Practices Using C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32902595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com