从输入中获取一个数字和一个单位作为双精度和字符串——编程:使用c++的原则和实践



我一直在阅读Bjarne Stroustrup的编程:使用c++的原理和实践。这不是家庭作业,也不是学校的作业。

我对第四章的这个练习已经束手无策了。我应该从输入中获取一个数字和一个单位,将数字存储为双精度体,将单位存储为while循环中的字符串,并跟踪到目前为止看到的最大和最小的数字。对于一个字符的单位,如"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

好的,谢谢大家的帮助。

似乎这个问题是编译器/系统特定的。我的代码在OSX的默认编译器中出现了问题,但在使用MinGW作为编译器的Windows 10上运行相同的代码却完美无缺。多奇怪的虫子啊。如果有人有任何关于如何让这个程序使用其默认编译器在OSX上工作的提示,我将非常感谢。

最新更新