你好......我试图在c ++中反转一个数字..... [英] Hello...i was trying to reverse a number in c++.....

查看:51
本文介绍了你好......我试图在c ++中反转一个数字.....的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我写cout<< rev;在while循环中,编译器给出了错误的答案但是当我写cout<< rev;在while循环之外,programm运行正常......

但是据我说它应该在循环中写入内部.....如果它是在外面写的应该给出一个单值回答..

ex如果我们给num的值为123

它应该返回1作为答案



< b>我尝试了什么:



when I write cout<<rev; inside the while loop , the compiler gives the wrong answer but when i write cout<<rev; outside the while loop the programm works fine......
but according to me it should be written inside while loop.....if it is written outside it should give a single value answer..
ex if we give num a value of 123
it should return 1 as answer

What I have tried:

int main()
{
   int num;
   int rev=0;
   cin>>num;
   while(num>0){
        rev=rev *10;
    rev=rev+num%10;
    num=num/10;
cout<<rev;
   }
   return 0;

推荐答案

在循环中连接 cout 中没有换行符连续值 rev 。由于 rev 是逐步构建的,因此输出看似错误。尝试:

In the loop you are concatenating (no newline in cout) successive values of rev. Since rev is built incrementally then you get a seeming wrong output.Try:
#include <iostream>
using namespace std;
int main()
{
  int num;
  int rev=0;
  cin>>num;
  while(num>0)
  {
    rev=rev *10;
    rev=rev+num%10;
    cout << (num%10);
    num=num/10;
  }
  cout << endl;

  return 0;
}


你的代码不正确,你不需要将任何东西乘以10,你只需要捕获<$ c的模数值每次迭代时$ c> num 。类似于:

Your code is incorrect, you do not need to multiply anything by 10, you only need to capture the modulo value of num on each iteration. Something like:
while(num>0){
    rev= num%10;
    num=num/10;
    cout<<rev;
 }


引用:

时我写cout<< rev;在while循环中,编译器给出了错误的答案但是当我写cout<< rev;在while循环之外,programm工作得很好......

when I write cout<<rev; inside the while loop , the compiler gives the wrong answer but when i write cout<<rev; outside the while loop the programm works fine......



编译器不给出答案,无论是对还是错。

答案来自已编译的程序。



使用调试器查看代码正在执行的操作。它允许你逐行执行第1行并在执行时检查变量。



调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。

调试器中没有魔法,它没有找到错误,它只是帮助你。当代码没有达到预期的效果时,你就会接近一个错误。


The compiler don't give answer, good or wrong.
The answer comes from the compiled program.

Use the debugger to see what your code is doing. It allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.


这篇关于你好......我试图在c ++中反转一个数字.....的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆