简体   繁体   English

在c ++中,如何确定将八进制数字转换为十进制时何时退出循环?

[英]In c++ , how do I determine when to exit my loop while converting octal numbers to decimals?

Please keep in mind that I am pretty much brand new to C++ and this is just a program i have to do for my class. 请记住,我几乎是C ++的新手,这只是我在课堂上要做的一个程序。 I think i understand how I would actually do it. 我想我知道我该怎么做。 I am just not sure what to put as my control condition for my while loop. 我只是不确定在while循环中将什么作为控制条件。 I am supposed to be able to convert any octal number given, so how do know when I'm at the first number and should stop? 我应该能够转换给定的任何八进制数,那么如何知道我何时在第一个数并且应该停止? I am moving forward numbers from right to left using increasing units of %10 (aka %10, %100,%1000), but how do I know when I should stop doing that? 我正在使用递增单位%10(又名%10,%100,%1000)从右向左移动数字,但是我怎么知道何时应该停止这样做呢? Like for the number 112 I would need to do %10, %100, and %100, but not past that. 就像数字112一样,我需要执行%10,%100和%100,但不能超过该范围。

#include <iostream>
#include <cmath>
using namespace std;

int main ()
{
  cout <<"Please enter the octal number to be converted: " <<
  int octal;
  cin >> octal;

   int remainder = 0;
   int modular = 10;

  int conversionToDecimal = 0; 
  while(modular < ***********)
  remainder = octal%modular;
  if (remainder < 10)
  {
   conversionToDecimal = conversionToDecimal + (remainder *(int)pow(8.0,count));
    count = 0;
    modular = modular*10;
  }
  else
  {
    remainder = remainder/10;
    count++;
  }

Obviously the program is not complete that is just the code I got to when I discovered my problem. 显然,该程序并不完整,仅仅是我发现问题时得到的代码。 I put the * where I am needing help with the code. 我将*放在需要代码帮助的地方。 Thanks so much! 非常感谢! In short, how should I control my loop so that I do not step off the front of the octal number? 简而言之,我应该如何控制循环,以免走出八进制数字的开头?

You could use the same way as when converting a number to a string of decimal digits: An array with a digit per index. 您可以使用与将数字转换为十进制数字字符串时相同的方法:每个索引具有一个数字的数组。 For each iteration, you take the modulo of 10, and store that digit, then divide by 10. When then number is zero (at the end of the loop), you're done. 对于每次迭代,取10为模,然后存储该数字,然后除以10。然后,当数字为零时(在循环末尾),就完成了。

Then take a digit at a time out of the array, and multiply your "total" by 8, add the current digit. 然后一次从数组中取出一个数字,然后将“总数”乘以8,然后加上当前数字。 When you have no more digits left, you're done. 如果您再也没有数字了,那就完成了。

I'll leave it to you to write the actual code to do this - after all, you're the one learning programming - I've been doing it for 30+ years. 我将留给您编写执行此操作的实际代码-毕竟,您是一个学习编程的人-我从事此工作已有30多年了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM