比较C++中的双打和字符
Comparing Doubles and Chars in C++
我正在尝试用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
cin
到double
变量中,则输入char
将保留在输入缓冲区中,double
变量保持不变。因此,这将以无限循环结束。
如果确实希望用户输入char
到结束输入,则需要将整个输入放入字符串变量中。检查字符串中是否有q
。如果不存在,请使用 atof() 将其转换为双精度。
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存