比较C++中的双打和字符

Comparing Doubles and Chars in C++

本文关键字:字符 C++ 比较      更新时间:2023-10-16

我正在尝试用C++编写一个简单的程序,该程序读取未指定数量的标记,然后一旦用户输入字符"q",程序必须计算并显示平均标记。但是我遇到了一些麻烦。我正在采取的方法是将每个值保存为双精度值,我想将双精度值与字符"q"进行比较,如果它们是相同的字符,则结束循环,计算并显示平均值。

但是,我认为标记的char值"q"和double值之间的比较似乎是无法比拟的。当我使用标记的整数值做同样的事情时,这对我有用,但似乎不是双倍。任何帮助将不胜感激。

这是代码:

int main()
{
    cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
    double total = 0;
    int counter = 0;
    bool repeat = true;
    do
    {
        double mark;
        cin >> mark;
        if (mark != 'q')
        {
            total += mark;
            counter++;
        }
        else
        {
            repeat = false;
        }
    }
    while (repeat == true);
    double average = total/counter;
    cout << "Average: " << average << endl;
    return 0;
}

您需要将 mark 变量更改为字符串,然后将其与"q"进行比较,否则尝试解析为数字。

否则整个代码没有多大意义,因为 ASCII 中的"q"是 113,我想这是一个可能的值

类型转换双倍到 int 然后比较,它必须工作,因为它比较字符的 ASCII 值

这是代码:

 int main()
{
cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
double total = 0;
int counter = 0;
bool repeat = true;
do
{
    double mark;
    cin >> mark;
    if ((int)mark != 'q')
    {
        total += mark;
        counter++;
    }
    else
    {
        repeat = false;
    }
}
while (repeat == true);
double average = total/counter;
cout << "Average: " << average << endl;
return 0;
}

您不能将双精度转换为字符。您可能需要使用其他 c++ 库函数将字符串 (char*) 转换为双精度。有不同的方法可以做到这一点。 试试这个:

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
    double total = 0;
    int counter = 0;
    bool repeat = true;
    do
    {
        char userinput[8];
        cin >> userinput;

    std::stringstream ss;
    double mark;
        if (userinput[0] != 'q')
        {
            ss << userinput;
            ss >> mark;
            total += mark;
            counter++;
        }
        else
        {
            repeat = false;
        }
    }
    while (repeat == true);
    double average = total/counter;
    cout << "total : " << total  << " count : " << counter << endl;
    cout << "Average: " << average << endl;
    return 0;
}

你做错了。如果尝试将char cindouble变量中,则输入char将保留在输入缓冲区中,double变量保持不变。因此,这将以无限循环结束。

如果确实希望用户输入char到结束输入,则需要将整个输入放入字符串变量中。检查字符串中是否有q 。如果不存在,请使用 atof() 将其转换为双精度。