为什么在其他输出线之间得到"1"输出?
Why am I getting a "1" output in between the other output lines?
我对C++很陌生,我正在尝试制作一个简单的数字阅读程序,它是功能性的。但是,我在其他输出行之间不断得到"1"输入。如何删除这些 1?
这是我的代码:
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
printf("nThe following program should enter integer numbers until a negative number.n");
printf("The output is the smallest number input as well as the number of numbers.nn");
printf("Please enter a number -----> ");
int n = 0;
int num;
cin >> num;
int smallest = num;
while (num >= 0)
{
n++;
if (num < smallest)
{
int smallest = num;
}
cout << "Please enter another number -----> " << (cin >> num) << endl;
}
while (num < 0)
{
cout << "Negative number entered. Calculating Results...nn";
cout << "Of " << n << " numbers read, the smallest number is " << smallest << ".n";
return 0;
}
}
输出如下所示(我随机输入了一些测试数字(:
The following program should enter integer numbers until a negative number.
The output is the smallest number input as well as the number of numbers.
Please enter a number -----> 3
Please enter another number -----> 4
1
Please enter another number -----> 8
1
Please enter another number -----> -1
1
Negative number entered. Calculating Results...
Of 3 numbers read, the smallest number is 3.
'''
如何删除这些 1,为什么会发生?
(cin >> num)
此表达式执行两项操作:
cin
输入流等待用户输入并将该值放入num
。istream
上>>
的运算符重载返回一个istream&
,一个对cin
实例的引用。
(这就是为什么您可以在一行上重复>>
运算符以获取多个值的原因。
该表达式位于cout <<
运算符需要参数的位置,因此从istream&
到某种可打印字符的转换会导致将1
添加到cout
流中。
1
位于新行上的原因是,您使用的终端/控制台要求您使用 Enter 键(添加新行(输入值。
我在 c++ 控制台中尝试了这个,并且不得不在第 25 行进行更改。而不是-
cout << "Please enter another number -----> " << (cin >> num) << endl;
我用了这个——
cout << "Please enter another number -----> ";
cin >> num;
并且没有明确的错误消息。另外,没有 1s。
不过,我有点担心实际的代码。逻辑不正确。
你是如何编译这段代码的?
Doc.cpp:26:60:错误:与"运算符<<"不匹配(操作数类型为"std::basic_ostream"和"std::basic_istream::__istream_type {aka std::basic_istream}"( cout <<"请输入另一个数字----->" <<(cin>> num( <<endl;
我必须更改此行:
cout << "Please enter another number -----> " << (cin >> num) << endl;
进入这个:
cout << "Please enter another number -----> ";
cin >> num;
cout << endl;
为了使代码可编译,至少对我来说是这样。
此外,最后一个 while 循环是不必要的,因为如果 num 不大于或等于零,则它只能是一个负数。
相关文章:
- 为什么在其他输出线之间得到"1"输出?
- 如何在 的开头<x>和结尾<y>之间更改带有文件输出的字符串的值
- 如何使用 ALSA API 在应用程序中在单声道和立体声之间切换声音输出?
- 如何包含整数之间的空格作为输出
- Raku中C++和NativeCall之间的输出不同
- 无法在同一行上获取输出,在 C++ 中两个输出之间有空格
- 尝试查找数组中点之间的最小距离时的随机垃圾输出
- 为什么两个相同的代码给出不同的输出,而它们之间的唯一区别是不同的变量名称和写作样式
- 将线程之间的标准输入/输出重定向
- 提升正则表达式 cpp 用于查找 %% 之间的字符串,输出不包括 % 字符本身
- 这些代码之间的区别在哪里?输出不应该是一样的吗?
- (c++) 返回和函数输出之间的错误
- 在 c++ 中反转数组时,为什么在输入和输出之间得到一个"random"数字?
- GCC和MSVC之间的文件输出不一致
- 可视化GDB在MSVC2012和GCC 7.3.1之间打印不同的C++输出
- C++子级在复制构造函数和输出之间的某个时间点更改父成员
- g++输出和Visual Studio输出之间存在差异.浮点变量
- 这两个程序的输出之间有什么区别以及为什么
- 在输入和输出之间使用不同数量的样本对音频ffmpegc++进行编码
- Qt:调试和发布中moc输出之间的差异