检索整数变量的值
这可能很容易弄清楚,但由于某种原因,我在任何地方都找不到解决方案。也许我没有在寻找正确的东西。也许是在一些我没有看过的初学者教程中。
不管怎样,我想知道如何在 C++ 中检索整数变量的值?我知道您可以使用 cin.getline() 来表示字符串变量,但是当我尝试使用整数变量时,我收到了一条错误消息(理所当然,我知道这是错误的,但我正在寻找以获得解决方案)。
我的项目是一个 Win32 控制台应用程序。我想做的是要求用户输入一个数字,存储在变量n
中。然后我获取 n
的值并用它执行各种数学函数。在我的头文件中,我有 string
、windows
、iostream
、stdio
、math
> 和fstream
。我需要添加另一个库吗?
编辑:
cout << "TEST SINE";
cout << "\nPlease enter a number.\n\n";
cin >> n;
break;
这是我尝试使用的代码。这就是我需要做的全部吗?如果是这样,我如何合并该变量,以便可以使用 sin、cos 和 tan 对其进行测试?
再次提前致谢。
This is probably easily figured out, but I can't find a solution anywhere, for some reason. Perhaps I'm not searching for the right thing. And maybe it's in some beginner tutorial I haven't watched.
Anyway, I was wondering how to retrieve the value of an integer variable in C++? I know you can use cin.getline()
for string variables, but I received an error message when I attempted that with an integer variable (and rightfully so, I know it was wrong, but I was looking for a solution).
My project is a Win32 console application. What I'm trying to do is ask a user to input a number, stored in the variable n
. Then I take the value of n
and perform various math functions with it. In my header file, I have string
, windows
, iostream
, stdio
, math
, and fstream
. Do I need to add another library?
EDIT:
cout << "TEST SINE";
cout << "\nPlease enter a number.\n\n";
cin >> n;
break;
Here's the code I'm trying to use. Is this all I need to do? If so, how do I incorporate the variable so I can test it using sin, cos, and tan?
Yet again, thanks ahead of time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这有什么问题吗?
对于数学函数,float 或 double 是更好的选择。
what is the problem with this?
For math functions, float or double would be better option.
如果你想要一个整数,你可以使用:
但是如果你想要一个健壮的应用程序,你最好控制输入数据。
也许更好的想法是将其作为字符串输入,就像您已经知道如何使用
getline()
一样,然后在调用等转换函数之前验证该字符串是否包含所有数字字符atoi() 或 strtol()。
这样,您可以获得可靠的输入以及所需的数据类型。
但是,如果您想使用三角函数,那么最好使用双精度数(
atof()
),而不是整数。下面是一个帮助您入门的示例程序:
示例运行如下所示:
If you want an integer, you can use:
but you had better have control of the input data if you want a robust application.
Perhaps a better idea would be to input it as a string as you already know how to do with
getline()
, then validate that the string consists of all numeric characters before calling a conversion function likeatoi()
orstrtol()
.That way, you get robust input plus the data types you want.
But, if you want to use trigonometric functions, you're probably better off working with doubles, with
atof()
, rather than integers.Here's a sample program to get you started:
Sample runs shown below: