为什么在其他输出线之间得到"1"输出?

Why am I getting a "1" output in between the other output lines?

本文关键字:输出 之间 其他 为什么      更新时间:2023-10-16

我对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)

此表达式执行两项操作:

  1. cin输入流等待用户输入并将该值放入num
  2. 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 不大于或等于零,则它只能是一个负数。